How to add React.js in Sage9

Hi there,

I’m trying to use react.js with sage 9. I found similar question here How to add React.js component in sage 9. Quick tutorial

Tried to set the react environment by following the steps mentioned in this tutorial by @Jacek but seems like react hooks are not working correctly with this solution and whenever I use any of the react hooks it will log an error to the browser console: “Invalid hook calls” (Attached the screenshot of error logs)

Can anyone please let me know how can I fix this or what are the better ways to set up react with sage 9?
Is react.js setup with all its functionalities possible with sage 9?

Sage Version: 9.0.9
React: 18.2.0
ReactDOM: 18.2.0

Hey @Suraj_Sanwal,

I’ve checked older test project on Sage v9.0.9 and I set useState hook - and it looks it works fine.
It may be several reasons why the hooks not working on your side, so you should check it step by step.

Bellow I present my test component and dependencies, maybe it will help you somehow.

/* eslint-disable */
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import { Button } from 'react-bootstrap';
import Header from './components/Header';
import Home from './components/Home';
import ProjectList from './components/ProjectList';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

  function Index() {

    const [count, setCount] = useState(0);

    const handleClick = () => {
        setCount(count + 1);
    }

    return (
        <div className='page-container'>
          <h1>XYZ</h1>
          <Button onClick={handleClick}>Click me</Button>
          <p>You clicked {count} times</p>
          <div>
              <Header />
              <BrowserRouter>
              <div>
                  <Switch>
                      <Route exact path='/' component={Home} />
                      <Route exact path='/project-listyy' component={ProjectList} />
                  </Switch>
              </div>
              </BrowserRouter>
              </div>
        </div>
    );
  }

  export default Index;

  if (document.getElementById('react-app')) {
    ReactDOM.render(<Index />, document.getElementById('react-app'));
  }

  "dependencies": {
    "@wordpress/scripts": "^12.5.0",
    "axios": "^0.21.0",
    "bootstrap": "^4.5.3",
    "jquery": "^3.3.1",
    "node-sass": "^4.14.1",
    "popper.js": "^1.14.7",
    "react": "^17.0.1",
    "react-bootstrap": "^1.4.0",
    "react-dom": "^17.0.1",
    "react-router-dom": "^5.2.0"
  }

PS.

Right now I don’t have any active projects with Sage 9 and React, my current setup not working properly with older Node Sass etc. So it will be hard to me assist you to resolve this issue. Good luck!

2 Likes

Thank you so much for a quick reply @Jacek

Yes. I Checked and am able to fit it now.
So basically I just moved my app component rendering from the app.js file to the main.js and fixed the issue for me.

Thanks again!

2 Likes