Home > Net >  Not able to pass function to child component in React
Not able to pass function to child component in React

Time:01-09

I don't understand what is happening, the syntax seems to be right, but I'm receiving this error:

TypeError: chooseMessage is not a function

// PARENT COMPONENT

import React, { useState } from 'react'


export default function LayoutMain(props) {

    const [message, setMessage] = useState("Hello World");

    const chooseMessage = (message) => {
        setMessage(message);
    };


    return (
        
        <div>
            <LayoutMenu>
                 <Navigator chooseMessage={chooseMessage} />
            </LayoutMenu>
        </div>
    )
}



//CHILDREN COMPONENT

export default function Navigator({chooseMessage}) {
   
    let msg = 'Goodbye';
    
    return (
  
            <div className='navigator-header' onClick={() => chooseMessage(msg)}>
                 test
            </div>
    )
}

I've read articles about lifting state up and also watched some videos and followed the instructions carefully over and over again but had no success.

#NEW UDPATE

I just realized that my code is definitively correct, it must be something related to the compiler or something.

CodePudding user response:

You could pass setMessage from the parent down to the child, then you can use the message state in the parent, and pass message down to the child if you want to use it in the child as well.

export default function LayoutMain (props) {
    const [message, setMessage] = useState('Hello World');

    return (
        <div>
            <LayoutMenu>
                <Navigator setMessage={setMessage} />
            </LayoutMenu>
            <p>{ message }</p>
        </div>
    )
}

export default function Navigator({ setMessage }) {
    const chooseMessage = (message) => {
        setMessage(message);
    };
    
    return (
        <div className='navigator-header' onClick={chooseMessage('Goodbye')}>
            test
        </div>
    )
}

CodePudding user response:

Seems like the code is working fine. However, you can control all the logic from one component that can be a parent controller and expose methods as props to interact with them it will be easier to manage the state there.

https://codesandbox.io/s/tender-smoke-57v1bk?file=/src/App.js

  • Related