Home > Enterprise >  Render a different image each time the user selects an option in React.js
Render a different image each time the user selects an option in React.js

Time:10-20

I have a form with a select with multiples options. I want that every time the user clicks on any of the options, the image to the right of the form changes.

The thing is that every time I select an option, the name of the variable is placed in the SRC of the image and not the path of the image itself. And also it doesn't seem to render every time I select an option.

This is my function code:


import ledger1 from '../media/ledger1.png'
import ledger4 from '../media/ledger4.png'

const RarityMenu = () => {

  const [ imgselected, setimg ] = useState({
    color:'',
    background:'',
  });

const { color, background } = imgselected;

 const getImageData = (e : any) => {
    setimg({  
      ...imgselected,
      [ e.target.name ] : e.target.value
    })
   }

And this is how I try to change the image url

return (
<div>
 <form>
  <label>Color</label>
  <select
  name="color"
  value={color}
  onChange={getImageData}
  >
   <option value="ledger1">Color1</option>
   <option value="ledger4">Color2</option>

  </select>
 </form>
</div>

<div>
 <img src={imgselected.color}/>
</div>

This outputs this:

<img src="ledger4">

instead of:

<img src="/static/media/ledger1.fef74bb8.png">

Any idea what i'm doing wrong?

CodePudding user response:

You are passing to your function getImageData() the value of the option selected, which is in your case string with same name as image variable, so you are not passing the variable that contains the string of the image, you are just passing a string similar to the name of the variable. so what I'm suggesting is to use the variable of the image, for example ledger1 as value in the option component like this : <option value={ledger1}>Color1</option>

return (
 <div>
  <form>
   <label>Color</label>
   <select
   name="color"
   value={color}
   onChange={getImageData}
   >
    <option value={ledger1}>Color1</option>
    <option value={ledger4}>Color2</option>
   </select>
  </form>
 </div>

 <div>
  <img src={imgselected.color}/>
 </div>
)

CodePudding user response:

You can process like this, if you have only two options. But if you have several options you can use a local function to get the src value from selected option:

return (
<div>
 <form>
  <label>Color</label>
  <select
  name="color"
  value={color}
  onChange={getImageData}
  >
   <option value="ledger1">Color1</option>
   <option value="ledger4">Color2</option>

  </select>
 </form>
</div>

<div>
 <img src={imgselected.color === "ledger1" ? ledger1: ledger4 }/>
</div>
  • Related