Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
127
rated 0 times [  128] [ 1]  / answers: 1 / hits: 5879  / 3 Years ago, wed, july 21, 2021, 12:00:00

I want to use a useState hook to change the color of my react icons to blue in my sidebar upon clicking one of them. I tried this


const [changeColor, setChangeColor] = useState('blue');

and then in the return


<IconOuter onClick={() => setChangeColor(changeColor)}>

{item.icon}

I would like to know what I am doing wrong? Any help would be greatly appreciated. Thank you.


Upon further inspection, I styled using component styles, so this is my css for the icon. It looks like theres a span surounding the icons which may be easier to style.


const IconOuter = styled.span`
background-color: white;
border-radius: 5px;
padding: 10px;
width: 44px;
height: 44px;
left: 8px;
top: 8px;
`;

More From » reactjs

 Answers
2

When using the useState hook you create a variable and a method, the variable is used to store the state and the method to change the value of the variable. The variables initial value is gained from the value inside the useState hook and you can change that value latter by using the method you defined from the useState hook


This is the basic form of the useState hook:


const [state, setState] = UseState(<initial state>)

So your code should be :


const [myColor, setmyColor] = useState('white'); //the color is currently white

<IconOuter onClick={() => setColor('blue')} />

const IconOuter = styled.span`
background-color: ${ myColor };
border-radius: 5px;
padding: 10px;
width: 44px;
height: 44px;
left: 8px;
top: 8px;
`;

[#1073] Wednesday, July 14, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
makaylahk

Total Points: 166
Total Questions: 94
Total Answers: 117

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
;