Skip to content

How user string input will show as background color in a div in react JS functional component

I am trying to make a color box where users can input color as a string but will display output as a background color in react I tried this way but it did not work as expected I am just learning to react. thanks in advance Here is my code.

import "./styles.css";
import randomColor from "randomcolor";
import { useState } from "react";
let color = randomColor();
// const name = "rocky";
export default function App() {
  const [statecolor, setcolor] = useState({

  function displayColor(e) {
    const inputcolor =;
    if (inputcolor === color) {
      setcolor( prevValues => {
        return { ...prevValues,bg:color,dis:true}
     } )
      console.log("not found")
  return (
    <div className="App">
      <h1>show color with input matching</h1>
        return (
          <h2 style={{backgroundColor:statecolors}}>{statecolors}</h2>
      <input type="text" value={statecolor} onChange={displayColor} />

); }


I’m not sure this is what you want to achieve, but here’s what I wrote

  • randomColor is unused actually because you doesn’t want to display initially right?
  • I’m not sure why checking this inputcolor === color, it will always go to else (unless you know what the randomColor will be) so I skipped that part