'Creating Dependendable react select dropdown

Just stuck in Creating a react dependent select field in reactjs from the array data.i have created a react field for name from data ,Now i want to create a dependent another select field i.e colour which value depend upon first Name select field and if two field are given then price should be shown?

code

const[name,setName]=useState("")
const[colour,setcolour]=useState("")
const data=[
  {id:1,name:"sandro",colour:"red",price:40000},
 {id:2,name:"sandro",colour:"white",price:4000},
{id:3,name:"suzuki",colour:"blue",price:8000},
{id:4,name:"Alto",colour:"gray",price:1000},
{id:5,name:"suzuki",colour:"red",price:5000},
]
const options=data.map((item)=>{
  return {
    label:item.name,
    value:item.id,
  }
})
const colours=data.map((item)=>{
  return {
    label:item.colour,
    value:item.id,
  }
})
<td width="200px">
        <Select
          options={options}
          value={ {label: item.name, value: id,}}
          onChange={(e) => {
            const res = {
              id: e.value,
              name: e.label,
            };
          setName(res)
        setColour(res)
          }}
        />
      </td>

<td width="200px">
        <Select
          options={colours}
          value={ {label: item.colour, value: id,}}
          onChange={(e) => {
            const res = {
              id: e.value,
              name: e.label,
            };
             setcolour(res)
          }}
        />
      </td>

<td>{data.price}<td/>

expected output

Name dropdown colourDropdown price



Solution 1:[1]

Here you use condition name and then condition for show price name and color. It will work.

const[name,setName]=useState("")
const[colour,setcolour]=useState("")
const data=[
    {id:1,name:"sandro",colour:"red",price:40000},
    {id:2,name:"sandro",colour:"white",price:4000},
    {id:3,name:"suzuki",colour:"blue",price:8000},
    {id:4,name:"Alto",colour:"gray",price:1000},
    {id:5,name:"suzuki",colour:"red",price:5000},
]
const options=data.map((item)=>{
    return {
        label:item.name,
        value:item.id,
    }
})
const colours=data.map((item)=>{
    return {
        label:item.colour,
        value:item.id,
    }
})
<td width="200px">
<Select
  options={options}
  value={ {label: item.name, value: id,}}
  onChange={(e) => {
    const res = {
      id: e.value,
      name: e.label,
    };
  setName(res)
setColour(res)
  }}
/>
</td>

{
name &&
<td width="200px">
<Select
  options={colours}
  value={ {label: item.colour, value: id,}}
  onChange={(e) => {
    const res = {
      id: e.value,
      name: e.label,
    };
     setcolour(res)
  }}
/>
</td>}

{(name && colour) && <td>{data.price}<td/>}

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 Joundill