bazi bazi - 9 days ago 6
React JSX Question

reactjs: how to define componentDidMount inside ES6 const?

I have this react component that is not an ES6

class
. It's a
const
like :

import React from 'react';
import Dashboard from './components/Dashboard';

const Home = (props) => {

const componentDidMount = () => {
console.log('component mounted'); // not working
}


return <Dashboard />;
}


Inside this const how do i define the
componentDidMount
function like i would do in a normal ES6
class
? this is how i did it before.

import React from 'react';
import Dashboard from './components/Dashboard';

class Dashboard extends React.Component {

componentDidMount() {
console.log('component mounted');
}

render() {
return <Dashboard />;
}

}

Answer

Stateless functional components don't support the lifecycle methods.

You can either convert it to a stateful component or wrap it in a stateful container.

Good example of wrapping to get the lifecycle methods:

https://egghead.io/lessons/javascript-redux-fetching-data-on-route-change