0

What I'm trying to do is to pass an id of a client to the parent component when the user selects a client.

In the child component, I receive the data with Axios, and I put the data in the <Listbox /> so the user can select it.

Select.js

export default function SelectPlayer() {

  const [client, setClient] = useState([])
  const [selected, setSelected] = useState(client[0])
  

  useEffect(() => {
    const params =
      "userName=" +
      currentUser +
    setClient([]);

    axios
      .get(API + params)
      .then((response) => {      
        const { data } = response;
        setClient(data);
      })
      .catch((error) => console.log(error.message));
  }, []);

return(
  <Listbox value={selected} onChange={setSelected}>
      {({ open }) => (
        <>
          <Listbox.Label>Select a Player:</Listbox.Label>
          <div">
            <Listbox.Button>
              {selected != undefined ? <span>{selected.client_name}</span> : 'Select'}
            </Listbox.Button>
  <Listbox />
);

How can I pass selected.client_id to another component?

ingjo12
  • 45
  • 6

2 Answers2

0

You can not pass up the chain in react, but you can pass a callback function down into the child component which will trigger an action. See this SO thread on how to do that.

Think in terms of state - the callback you pass to the child/children could be an onClick handler - the onClick handler could dispatch an action which updates selected.client_id to be the id of the client that the onClick handler is triggered by - make sense?

Jeremy
  • 1,170
  • 9
  • 26
0

If you need to pass selected id to parent component, you can do it like this:

export default function SelectPlayerPARENT() {
  const [selectedClientId, setSelectedClientId] = useState(null);

  return(
      <SelectPlayer setSelectedClientId={setSelectedClientId} />
  )
}

and then in your child component you should replace this lines

export default function SelectPlayer() {

<Listbox value={selected} onChange={setSelected}>

with this lines

export default function SelectPlayer(props) {

<Listbox value={selected} onChange={props.setSelectedClientId}>

So what happend here, is that you created setSelectedClientId function in parent and passed it down trough props in child, and then you called it on your onChange handler.

In case that you want to send this selected id in component that is (not parent) and it is further apart in component tree you might consider something a little bit more advanced like context API, useReducer or even if this case will happen often in project, state management like Redux.

Wings
  • 502
  • 4
  • 14