Home > Blockchain >  Update two objects if specific select option is chosen in drop-down for React Create Form
Update two objects if specific select option is chosen in drop-down for React Create Form

Time:04-19

I'd like to have a create form where if the user selects a specific cuisine, it will automatically push the designated cuisine Image into the form in React. I'm new to react. See below useState setup:

useState:

const Create = (props) => {
    const cuisine = ['Indian', 'American', 'Thai', 'Mexican', 'Spanish', 'Chinese'];
    
    const [form, setForm] = useState({
        cuisine: cuisine[0],
        cuisineImg: "",
})

My onChange Handler:

    const onChangeHandler = (e) => {
        setForm({
            ...form,
            [e.target.name]: e.target.value
        })
    }

Then here is my return:

return (
   <select name="cuisine" className="form-select my-3" onChange={onChangeHandler}>
      <option disabled selected value> -- Select a Cuisine -- </option>
    {
      cuisine.map((cuisine, i) => {
       return <option value={cuisine} key={i}> {cuisine}</option>
       })
    }
  </select>) 
}

When the user selects "Indian" for example, I want to push "Indian.jpg" as value for key 'cuisineImg' when form is submitted. ('American' selected then push 'American.jpg' and so forth). Do I use a selectHandler? And if so, how?

Thanks in advance for your help.

CodePudding user response:

The filename is just a string, so if the images are named consistently with the array values you should be able to do this in setForm:

const cuisine = e.target.value

const [form, setForm] = useState({
  cuisine: cuisine,
  cuisineImg: `${cuisine}.jpg`,
})

This is just concatenating the string cuisine and .jpg for the image. In your onChangeHandler function, e.target.value will be equivalent to Indian or American etc.

  • Related