How to render multiple div background color change with div id

Viewed 526

While onclick the div background color will change to blue again click the div color will change to white.. with dynamic id... please help how can I do in reactjs

jQuery code:

$(document).ready(function($){
    $('#my_checkbox').on('change',function(){
      if($(this).is(':checked')){
        $("#card").css('background-color',"blue");
      }else{
        $("#card").css('background-color','white');
      }
    })
  }) 
2 Answers

In react you simply use the component state in 2 ways

Function Component

import React, { useState } from 'react'

function SomePage() {
  const [toggle, setToggle] = useState(false)

  return (
    <div>
      <button onClick={() => setToggle(!toggle)}>Click Me</button>
      <div style={{ color: toggle ? 'red' : 'blue' }}>my color is changed</div>
    </div>
  )
}

Class Component

import React from 'react'

class SomePage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      toggle: false
    }
  }

  render() {
    return (
      <div>
        <button onClick={() => this.setState({ toggle: !toggle })}>Click Me</button>
        <div style={{ color: this.state.toggle ? 'red' : 'blue' }}>my color is changed</div>
      </div>
    )
  }
}

this is the basic level of react, you should adjust to your needs

$(document).ready(function($){
    $('#my_checkbox').on('change',function(){
      if($(this).is(':checked')){
        $("#card").css('background-color',"blue");
      }else{
        $("#card").css('background-color','white');
      }
    })
  }) 
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id ="card" style="height:300px;width:200px;">
 <input type="checkbox" id="my_checkbox" />
</div>
</body>
</html>

Related