Skip to content
Advertisement

How do I use the useState hook to change the color of my react icons to blue?

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;
`;

Advertisement

Answer

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;
`;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement