React useState with dropdown

i have a code that is changing image

 const [cars] = useState([
    {
      title2: "Sahara Brown",
      image: "images/brown.jpg",
    },
    {
      title2: "Carbon Black",
      image: "images/black.jpg",
    },
    {
      title2: "SPL Green",
      image: "images/gren.jpg",
    },

    {
      title2: "Ghost White",
      image: "images/white.jpg",
    },
  ]);
  const [carImage, setCarImage] = useState(cars[0].image);

<div class="image-wrap">
        <img 
        id="cars"
        src={carImage} setCarColor={setCarColor} setCarImage={setCarImage} />
      </div>

 <select
        onChange={() => {setCarImage(car.image); setCarColor(car.title2);}}
        value={carImage}
        id="variation-select"
      >
        {cars.map((car) => (
          <option data-color={car.title2} value={car.image}>{car.title2}</option>
        ))}

            
      </select>

when i change the option the image changes im okay with that but as you can see there is title2 on there i want to get both what imean by that is it will both change the image and set the title as that title how can i do that i want to use both image and the title.

thank you.

Hi there. I am not sure what you are using your onChange function on but you will probably need to make sure that whichever image gets called, the corresponding title2 also gets pulled. For example if you are getting the image associated with car[0] you will want the title2 for car[0]. You can use a Math method if what you are wanting to pull is random and then apply it to what you are returning or a map or loop if you want to pull them in order. Hope this helps.

Hello there,

I am not sure if this is just an issue, because you copied your code over here, or if this is an issue in your production code:

  • This is not a good/useful way to use useState:
const [cars] = useState([{title2: "Sahara Brown", image: "images/brown.jpg", }...]);
  • In this line, setCarColor is not defined:
<img id="cars" src={carImage} setCarColor={setCarColor}... />
  • In this line, both car and setCarColor are not defined:
onChange={() => {setCarImage(car.image); setCarColor(car.title2);}}

I highly recommend you share all of your code relevant to this problem.

Hope this helps

As pointed out you have errors in your code.


One option might be to use the options.selectedIndex property to get the index of the option element that was selected and use that index for the car array. That way you can get to whatever properties on the car object you need.

const handleChange = ({ target }) => {
  const index = target.options.selectedIndex;
  const { title2, image } = cars[index];

  setCarImage(image);
  setCarTitle(title2);
};

You really shouldn’t need the car array to be in state (unless we are missing some context from the code you posted).

Example

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.