I'm very new to react, and working on making something where there will be a button that you can press that will roll a dice. For now, I'm currently just trying to get the image to be clickable, and when you click on it, it 'rolls' the dice. However, my picture does not change on click, and I am not getting any errors in VSCode. Any help is appreciated.
import React from 'react'
import dice1 from './assets/dice1.png';
import dice2 from './assets/dice2.png';
import dice3 from './assets/dice3.png';
import dice4 from './assets/dice4.png';
import dice5 from './assets/dice5.png';
import dice6 from './assets/dice6.png';
function DiceRoll(e) {
var number = Math.floor(Math.random() * 6) 1;
switch(number) {
case 1: e.target.setAttricute('src', {dice1}); break;
case 2: e.target.setAttricute('src', {dice2}); break;
case 3: e.target.setAttricute('src', {dice3}); break;
case 4: e.target.setAttricute('src', {dice4}); break;
case 5: e.target.setAttricute('src', {dice5}); break;
case 6: e.target.setAttricute('src', {dice6}); break;
default: return <h1>Something went wrong</h1>
}
}
function App() {
return (
<img
src={dice1}
onClick={DiceRoll}
/>
);
}
export default App;
CodePudding user response:
You have a typo, e.target.setAttricute
should be e.target.setAttribute
.
Here is a better strategy for doing this. It utilizes the React.useState
hook.
const dice = [die1, die2, die3, die4, die5, die6];
function App() {
const [srcImg, setSrcImg] = React.useState(die1);
const rollDie = () => {
const randNum = ~~(Math.random() * dice.length);
setSrcImg(dice[randNum]);
}
return <img src={srcImg} onClick={rollDie} />;
}
CodePudding user response:
You can do it in following way
import { useState } from "react";
const imgs = [
"https://via.placeholder.com/350x150",
"https://via.placeholder.com/240x160",
"https://via.placeholder.com/480x240",
"https://via.placeholder.com/350x150",
"https://via.placeholder.com/240x160",
"https://via.placeholder.com/480x240"
];
export default function App() {
const [src, setSrc] = useState(0);
const rollDice = () => {
const number = Math.floor(Math.random() * imgs.length);
setSrc(number);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>{src}</h2>
<img src={imgs[src]} alt="img" onClick={rollDice} />
</div>
);
}
I've created Sandbox with same. https://codesandbox.io/s/awesome-water-03xwz