M.El Yaakoubi
M.El Yaakoubi

Reputation: 181

passing props from parent to children in react

I want to pass props from parent to several children components , but eventually I get the error of Cannot read properties of undefined (reading 'props') App.js :

  render() {
    const {currentUser} = this.props
    return (
      <div id="App" className='loader'>
        <BrowserRouter>
            <Routes>
              <Route path='women' element={<Women currentUser={currentUser} />} />

Women.js:

  render() {
    const { isLoading } = this.state;
    if (isLoading) {
        return null;
    }
    const {currentUser} = this.props

    return (
        <div>
            <div className='container mx-auto'>
                <HomeHeaderW style={{ backgroundColor: "#fff2e0" }} currentUser={currentUser} />

HomeHeaderW.js :

function HomeHeaderW() {
   const {currentUser} = this.props
   const [isLogged, setLogged] = useState(false);
   useEffect(() => {
     if(currentUser) {
         setLogged(true)
     }
   });

I don't know why I get the undefined error , do you have an idea about this ? Or Am I doing it in the wrong way

Upvotes: 0

Views: 430

Answers (1)

Nick Vu
Nick Vu

Reputation: 15540

HomeHeaderW is a function-based component (Women and App are class-based components), you cannot get props from this.props

You should pass your props on the params

function HomeHeaderW(props) {
  const {
    currentUser
  } = props;

  const [isLogged, setLogged] = useState(false);
  useEffect(() => {
    if (currentUser) {
      setLogged(true)
    }
  });

You can check this document for a better understanding

Upvotes: 1

Related Questions