I am trying to build a random color generater with the randomcolor npm package. When a button is clicked a div should change its color randomly. But react doesn't let me use the randomColor function inside of my reatc component and I don't know why.
import './App.css';
import randomColor from 'randomcolor';
import { useState } from 'react';
import styled from 'styled-components';
function App() {
const [randomColor, setRandomColor] = useState('white');
const Generated = styled.div`
background-color: ${randomColor};
transition: all 0.3s;
padding: 4rem 8rem;
border-radius: 10px;
`;
return (
<Container className="App">
<Button
onClick={() => setRandomColor(randomColor({luminosity: "random", hue:"random"}))}
className="generate"
>
Generate
</Button>
<Generated>Generated Color: {randomColor}</Generated>
</Container>
);
}
export default App;
Does anyone know why it says "randomColor" is declared but never used and why I can't use it in my component?
CodePudding user response:
you have silly mistake, change your randomColor and SetRandomColor name javascript confused by the same name with randomColor() function is this correct of your code :
import './App.css';
import randomColor from 'randomcolor';
import { useState } from 'react';
import styled from 'styled-components';
function App() {
const [randomColor2, setRandomColor2] = useState('white');
const Generated = styled.div`
background-color: ${randomColor};
transition: all 0.3s;
padding: 4rem 8rem;
border-radius: 10px;
`;
return (
<Container className="App">
<Button
onClick={() => setRandomColor2(randomColor({luminosity: "random", hue:"random"}))}
className="generate"
>
Generate
</Button>
<Generated>Generated Color: {randomColor2}</Generated>
</Container>
);
}
export default App;