Roots Discourse

How to add React.js component in sage 9. Quick tutorial

I didn’t find a tutorial on how to attach react components in Sage, so here’s a short tutorial. Maybe it will be useful for someone.

1. Install babel-eslint and update .eslintrc.js

yarn add babel-eslint

2. install react-router-dom

yarn add react-router-dom

3. Update eslintrc.js ‘parser’: ‘babel-eslint’ before ‘parserOptions’

  'parser': 'babel-eslint',

4. In config.json add new asset for react js

"app": [
  "./scripts/app.js"
]

5. In setup.php enqueue new wp-element script.

// React render bundle
wp_enqueue_script('sage/app.js', asset_path('scripts/app.js'), ['wp-element'], time(), true); 

6. Create “app.js” file and folder “components” in /resources/scripts

7. Create some example files components: Home.js and ProjectList.js

Home.js

const Home = () => {
  return(
      <div className='main-footer'>
          <div className='container'>
              <h1>This is Home</h1>
          </div>
      </div>
  )
}
export default Home;

Project.js

const Project = () => {
  return(
      <div className='main-footer'>
          <div className='container'>
              <h1>This is project list</h1>
          </div>
      </div>
  )
}
export default Project;

8. In /resources/views/page.blade.php add:

<div id="react-app"></div>

9. Create two pages in wordpress with default-tempalate Home and Project List. The path to page should be the same as in react router “home”, “project-list”.

10. In app.js add components to render

/* eslint-disable */
const { render } = wp.element;
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import ProjectList from './components/ProjectList'

function App() {
  return (
      <div className='page-container'>
        <div>
            <BrowserRouter>
            <div>
                <Switch>
                    <Route exact path='/' component={Home} />
                    <Route exact path='/project-list' component={ProjectList} />
                </Switch>
            </div>
            </BrowserRouter>
        </div>
      </div>
  );
}

export default App;

render(<App/>, document.getElementById('react-app'));
/* eslint-enable */

11. yarn build, yarn start. Now each page should render components.

Of course that should be prettier solution to handle eslint error in components :stuck_out_tongue: but for testing should be fine. It not works as SPA so still you can mix react components with blades. In enqueue script the version is set to time() for developing. Have fun.