V
V
Vladimir2022-03-30 14:23:23
React
Vladimir, 2022-03-30 14:23:23

Related selects, how to clear on change?

There is a base in the car database in json, I was able to set up the selects so that when the car brand changes, the models are pulled up, but when the brand is changed, the models are not cleared.

Base fragment:

{  
   "AC": [
   "378 GT Zagato",
   "Ace",
   "Aceca",
   "Cobra"
  ],
  "Acura": [
   "CL",
   "CSX",
   "EL",
   "ILX",
   "Integra",
   "Legend",
   "MDX",
   "NSX",
   "RDX",
   "RL",
   "RLX",
   "RSX",
   "SLX",
   "TL",
   "TLX",
   "TSX",
   "ZDX"
  ],

And this is what I was able to do:
import { Select} from 'antd';
import { Option } from 'antd/lib/mentions';
import { useEffect, useState } from 'react';
import Cars from './Cars.json';


interface Icarlist{
  [key:string]:string[];
}
const Tables2 = () => {

const[brand, setBrand] = useState<string>("")
const[models, setModels] = useState<string>("")

const carlist: Icarlist={...Cars}

useEffect(()=>{

},;

  return (
    <div style={{ textAlign: 'center',marginBottom: 20 }}>
      <>
       <Select  
       style={{ width: 240 }}        
       placeholder="Select brand" 
       onChange={setBrand}>
       {Object.keys(Cars).map(brend => (
       <Option key={brend}>{brend}</Option>
        ))}
       </Select>
       
     <Select 
     style={{ width: 240 }} 
     placeholder="Select model" 
     onChange={setModels}>
     {carlist[brand]?.map(models => (
     <Option key={models}>{models}</Option>
        ))}        
       </Select>
       </>
    </div>
  );
  }

How can I use useEffect to reset the contents of the car model select when changing the brand?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Ne7Le4Der, 2022-03-30
@Dakkar-01

useEffect(()=>{
    setModels("");
}, [brand]);

If I understand you correctly

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question