'React: Newbie: OAP : process child button click call parent function

I come from the world of VB and other archaic languages and am trying to learn React/Javascript and have a simple problem - which I don't know how to solve, but I feel should be very simple.

I have a functional component which renders a dropdown and a button, when the dropdown changes I am using usestate to keep track of the select item.

I then have another functional component which 'hosts' this component - I guess the correct terminology is a parent. what I want to do is when the button is clicked I retrieve the dropdown item(which I have stored) and pass the value to a function in the 'host' component,which then does other stuff

but I cant for the life of me figure out how to do this :-(



Solution 1:[1]

If I'm understanding this properly you need to get data from the child component to the parent one.

You first of need to define the state in the parent component and then pass it down to the child component like so

const ChildComponents = ({state,setState}) => { // accepts the state and setState from the parent component
  return(
    <select onChange={(e) => setState(e.currentTarget.value)} value={state}>
      <option value=""></option>
      <option value=""></option>
      <option value=""></option>
    </select>
  )
}

const ParentComponent = () =>{
  const [state,setState] = useState();

  return <ChildComponents state={state} setState={setState} />
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frosty