Good afternoon, i am creating an interactive rating card with react. I have 5 divs wich represent the number you are rating. When i click on one number i want to change the background of the targeted div to white.
import './App.css';
import React, { useState } from 'react';
function App() {
const [color, setColor] = useState('blue');
const changeColor = () => {
setColor('white');
};
return (
<div className="card">
<div className="container">
<p class="question">How did we do?</p>
<p>
Please let us know how we did with your support request. All feedback
is appreciated to help us improve our offering!
</p>
<div id="numbers">
<div
className="circle"
onClick={setColor}
style={{ backgroundColor: color }}
>
1
</div>
<div
className="circle"
onClick={changeColor}
style={{ backgroundColor: color }}
>
2
</div>
<div className="circle">3</div>
<div className="circle">4</div>
<div className="circle">5</div>
</div>
<button className="btn"> Submit </button>
</div>
</div>
);
}
export default App;
so far i tried to work with an useState hook. I read in some other sources to use the e.target.value or to give every div a special key value. I tried it with both but didnt manged to solve it. At the moment div 1 and div 2 change the color if i click on one of them.
>Solution :
- Create a state called
target. - Create an array.
- Iterate the array and build a
divon top of it. - Whenever you click a
div, set the target state to the index. - Style the
divkeeping target state in mind.
The following code should do the job.
import './App.css';
import React, { useState } from 'react';
function App() {
const [target, setTarget] = useState(-1);
const divsArr = [1, 2, 3, 4, 5]
return (
<div className="card">
<div className="container">
<p class="question">How did we do?</p>
<p>
Please let us know how we did with your support request. All feedback
is appreciated to help us improve our offering!
</p>
<div id="numbers">
{
divsArr.map(index =>
<div
className="circle"
onClick={() => setTarget(index)}
style = {{backgroundColor: (index === target ? 'white' : 'blue')}}
>
{index + 1}
</div>
}
<button className="btn"> Submit </button>
</div>
</div>
);
}
export default App;