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.
JavaScript
x
36
36
1
import "./styles.css";
2
import randomColor from "randomcolor";
3
import { useState } from "react";
4
let color = randomColor();
5
// const name = "rocky";
6
export default function App() {
7
const [statecolor, setcolor] = useState({
8
bg:"",
9
dis:false
10
});
11
12
function displayColor(e) {
13
const inputcolor = e.target.value;
14
if (inputcolor === color) {
15
setcolor( prevValues => {
16
return { prevValues,bg:color,dis:true}
17
18
} )
19
}else{
20
console.log("not found")
21
}
22
}
23
return (
24
<div className="App">
25
<h1>show color with input matching</h1>
26
{statecolor.map((statecolors)=>{
27
return (
28
<h2 style={{backgroundColor:statecolors}}>{statecolors}</h2>
29
)
30
})}
31
32
33
<input type="text" value={statecolor} onChange={displayColor} />
34
</div>
35
36
); }
Advertisement
Answer
I’m not sure this is what you want to achieve, but here’s what I wrote https://codesandbox.io/s/laughing-thunder-jlc28?file=/src/App.js
- 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 toelse
(unless you know what the randomColor will be) so I skipped that part