0

So I have a select, which changes state value whenever I select something. This works perfectly, but since the select code is really massive and I have up to 6 selects per page I wanted to move it to another Component.

Here is how it looks like in 1 Component:

const [root1Select, setRoot1Select] = useState([[], []]);    
const root1Change = e => { setRoot1Select(e.target.value.split(',')); }
return(
  <div>
    <select id="root1" onChange={root1Change}>
    ...

And here is how I would like it too look:

App Component:

const [root1Select, setRoot1Select] = useState([[], []]);    
const root1Change = e => { setRoot1Select(e.target.value.split(',')); }
<SelectRoot />

SelectRoot Component:

return(
  <div>
    <select id="root1" onChange={root1Change}> //thats root1 from App Component
    ...
  • Hello Adam, why don't you use an object that has each property and when the value changes in each select, you only change said property and keep the others the same with the spread operator? – Jenaro Calviño Dec 03 '19 at 13:01
  • Would I be able to change object values from different Component then? – Adam Ostrowicki Dec 03 '19 at 13:06
  • Well, you change the values the same way you are doing now, you pass an event from the child to the parent and listen to that event, otherwise the state is not on th eparent but on the child. – Jenaro Calviño Dec 03 '19 at 15:58

2 Answers2

0

You can follow the code, the code actually work the pass props parent to children and children change to call the parent props or follow the link :

How to update parent's state in React?

App

const [root1Select, setRoot1Select] = useState([[], []]);    
const root1Change = e => { setRoot1Select(e.target.value.split(',')); }
<SelectRoot onChangeSelect={(e)=>root1Change(e)} />

SelectRoot Component:

function SelectRoot(props) {
   return <select id="root1" onChange={props.onChangeSelect}> .....
}
Md. Abu Sayed
  • 2,396
  • 2
  • 18
  • 26
0

maybe this is more in line with what you are trying to do. Keep in mind setting of a select doesn't trigger a rerender because of the way useRef works.

const Select = props => {
  return (
    <select
      id={props.id}
      onChange={e => {
        props.current[e.target.id] = e.target.value;
        console.log(props.current);
      }}
    >
      <option value="1">1</option>

      <option value="2">2</option>

      <option value="3">3</option>
    </select>
  );
};

const Root = () => {
  const selRef = useRef({});
  return (
    <div>
      <Select id="sel1" current={selRef.current} />
      <Select id="sel2" current={selRef.current} />
      <Select id="sel3" current={selRef.current} />
    </div>
  );
};```