Vered
Vered

Reputation: 21

React: function passed in props is undefined

I have a functional component with hooks, and I'm trying to pass the update function to another component, but it's always undefined. Here is a minimal example:

const A = () => {
    const [value, setValue] = React.useState(null);

    return (
        <div>
            <B value={value} setValue={setValue}/>
        </div>
    )
};

const B = (value: any, setValue: any) => {
    return (
        <Input value={value} onChange={e => setValue(e.target.value)}/>
    )
};

I've seen suggestions that involve binding or array functions, but neither work. How can I pass this function properly? Converting to a class component is possible, but in that case where do I define the hooks or what do I use instead? (All I really need is a stateful object that I can access and change from other components).

Thanks in advance.

Upvotes: 1

Views: 2548

Answers (2)

Viet Dinh
Viet Dinh

Reputation: 1961

Because parent component use param props same as {...prams} to pass it to child. Let try:

const B = ({value: any, setValue: any}) => {
    return (
        <Input value={value} onChange={e => setValue(e.target.value)}/>
    )
};

Upvotes: 0

Shmili Breuer
Shmili Breuer

Reputation: 4147

In component B you are destructuring value and setValue from props but you are missing the curly braces {} you need to add curly braces like this.

           // add                    // add
const B = ({value: any, setValue: any}) => {
    return (
        <Input value={value} onChange={e => setValue(e.target.value)}/>
    )
};

Upvotes: 1

Related Questions