Gabriel Donada
Gabriel Donada

Reputation: 449

how do I change a input children value component?

I’m wondering how can I change a children input value from main? Basically I have a component that I’m sending a children, and in this component I want to be able to change the input value.

Here is my main:

 <FooterOptions>
  <input type="text"
  onChange={event=>setState(event.target.value)}
  value={state}
  hidden/>
</FooterOptions>

And here is my component:

export function FooterOptions(props:{children: ReactNode}){
  return(
    <div>
      {props.children}
    </div>
  )
}

Upvotes: 0

Views: 391

Answers (1)

JuanCaicedo
JuanCaicedo

Reputation: 3438

The children prop is something that you can only render onto the page, so there's nothing you can do with it to change the value of the input.

Instead how I would think about this is that you want to provide a mechanism for FooterOptions to change the value of another component. Here it happens to also be rendered as its children, but it would work the same even if it was rendered someplace else.

const Parent = () => {
  const updateInput = (val) => setState(val)
  return (
    <FooterOptions handleUpdate={updateInput}>
      <input type="text"
        onChange={event=>setState(event.target.value)}
        value={state}
        hidden/>
    </FooterOptions>
  )
} 
export function FooterOptions(props:{children: ReactNode, handleUpdate}){
  // Example handler
  const handleClick = () => handleUpdate('updated inside FooterOptions')
  return(
    <div onClick={handleClick}>
      {props.children}
    </div>
  )
}

If you'd like to add more details of how you are hoping to update, then I can add a better example 😀

Upvotes: 1

Related Questions