Table of contents
Background color change project
This is a small project in which we will learn how to add tailwind and also how the onclick function work.
import { useState } from "react";
function App() {
const [color,setColor]=useState('olive');
function red(){
setColor("red");
}
function green(){
setColor("green");
}
return (
<div className="flex flex-col items-center justify-center h-screen" style={{backgroundColor:color}}>
<div className="fixed flex flex-wrap justify-center space-x-2">
<button
onClick={red}
className="gap-3 px-3 py-2 rounded" style={{backgroundColor:"red"}}>red</button>
<button
onClick={green}
className="gap-3 px-3 py-2 rounded" style={{backgroundColor:"green"}}>green</button>
<button
onClick={()=>setColor("blue")}
className="gap-3 px-3 py-2 rounded" style={{backgroundColor:"blue"}}>blue</button>
</div>
</div>
);
}
export default App
output -
In this code on clicking the button it will change the background color.
Note (important)
why we passed an arrow function inside the onclick why we not pass directly setColor with parameter ?
In React, it's common to use arrow functions inside event handlers like onClick
to avoid immediate invocation of the function when the component renders. Let me explain why:
If you directly call setColor
with a parameter inside the onClick
attribute, it will be called immediately when the component renders. This is not what you want; you want the setColor
function to be called only when the button is clicked.
By using an arrow function inside onClick
, you're creating a closure that captures the current value of color
and only executes setColor
when the button is clicked. This ensures that setColor
is called at the appropriate time, i.e., when the button is clicked, rather than immediately when the component renders.