Search code examples
reactjsmeteor

Describing React componentDidMount() in Meteor js syntax


How can i declarate componentDidMount without creating class extends react component? For example render() declarates with react-dom package, maybe is exist another package for componentDidMount?

class App extends Component {
  constructor(){
    // do something
  }
  componentDidMount(){
    // js code must run after page loaded
  }
  render(){
    return(
      <div className="app">

      </div>
    );
  }
}
export {App};

The same thing with component constructor()

const App = () => {

  // constructor and componentDidMount does not work here

  // js code must run after page loaded

  return (
    <div className="app">

    </div>
  );
};
export {App};

Solution

  • First of all, what you want to achieve is fully Meteor independent. It's a pure React problem that could exist with any backend. What you want to achieve can be done using the useEffect() hook for which you'll find the documentation right here:

    https://reactjs.org/docs/hooks-reference.html#useeffect

    Here is a great article explaining how to replace lifecycle methods with hooks:

    https://dev.to/trentyang/replace-lifecycle-with-hooks-in-react-3d4n

    In your case, for componentDidMount you'll have to do the following:

    useEffect(() => {
         // js code must run after page loaded
    }, []);
    

    In the final array you have to put dependency that will retrigger the hook if you need. To imitate a simple componentDidMount an empty array is generally the solution.