I want to toggle between default color and "blue" colors when I click on button in ReactJS

Viewed 617

I want to toggle the colors of my h1 tag. I can change the color one time to specific color. But I want to take the color to previous color when I click again.I used useState for that. In useState selected gives me true and false. According to true and false I create if statement and change the color. Here is my code

import './App.css';
import React, { useState } from 'react';

function Deneme() {
  const [color,setColor]=useState('red');
  const [selected, setSelected] = useState(false)
  const [textColor,setTextColor]=useState('white');
  if(!selected){
    setColor("blue")
  }
  return (
    <div className="App">
      <button style={{background:color}} className='btn btn-primary' onClick={()=>{setTextColor('red');setSelected(!selected)}}>Click here</button>
      <h1 style={{color:color}}>Change Color</h1>
    </div>
  );
}

export default Deneme;
2 Answers
import {useState} from 'react';
export default function App() {
const [color,setColor]=useState(true);
   return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <button onClick={()=>setColor(!color)}
          style={{color:color ? 'red':'blue'}}>clickme</button>
        </div>

); }

Just create a boolean state and on the base of boolean value change the color to red or blue.

Related