Alexmedkex
Alexmedkex

Reputation: 457

Passing value from React child to parent component, when event is triggered in parent?

I know that 'passing value from child to parent' is a common question, but I can't find an answer to my particular case.

Basically, I have a parent component which has a list of children which have input values.

function Parent() {

    function submit() {
        // make some API call with the values from the children.   
    }

    return (
        <Child></Child>
        <Child></Child>
        ...
        <Button onClick={submit}>Submit</Button>
    )

}

function Child() {
    return (
        <TextField></TextField>
    )
}

I'm aware that you would normally pass a function as prop to the children. That would work if the child knows when to call that function, but in this case the parent only knows because it has the button that triggers the event.

I could use an onChange event listener in the TextField inside the children, and constantly update the state in the parent whenever we change the text. But, this seems like a lot of complexity when I just want to get the values when we submit.

Upvotes: 0

Views: 62

Answers (1)

Kaca992
Kaca992

Reputation: 2267

If you don't want to use local state and onChange events (wich you said), you could use useRef and read the value directly. Look at this example:

https://gist.github.com/jamesreggio/142215754ad06f375bd87657c6227ed8

basically each of your child component would get ref wich it would forward to your input component, and then in submit you can directly access child value.

Hope this helps.

Upvotes: 2

Related Questions