Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reactjs: how to define componentDidMount inside ES6 const?

Tags:

reactjs

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 />;
    }

}
like image 767
bazi Avatar asked Dec 01 '16 07:12

bazi


1 Answers

To anyone else learning React and stumbling upon this in the future like me, the accepted answer here is out of date. Please see this question: componentDidMount equivalent on a React function/Hooks component?

If using React 16.8.0+ you can create the effect of componentDidMount by using the hook useEffect:

useEffect(() => {
  // Your code here
}, []);
like image 173
joe92 Avatar answered Sep 28 '22 04:09

joe92