Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't use imported randomColor function in react component

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading