11 February 2020

Reusable CheckBox component example in react js

  • Create Components folder under src folder
  • Create  common folder under Components folder
  • Create CheckBox folder under common folder 
  • Add index.js file under CheckBox folder and add below Code
import React from "react";
import "./style.css";

const CheckBox = props => {
  return (
    <div className="checkbox">
      <label>
        <input
          id={props.id}
          type="checkbox"
          value={props.value}
          checked={props.isChecked}
          onChange={props.onclickHandler}
        />
        {props.value}
      </label>
    </div>
  );
};

export default CheckBox;
  • Add style.css file and add below Code
// CSS Style here
  • Go to Components Folder and Add CheckBoxEXP.js file and add below Code
import React, { useState } from "react";
import CheckBox from "./common/CheckBox/index";

export default function CheckBoxEXP() {
  const [cb1setcb1] = useState(false);
  const [cb2setcb2] = useState(false);

  const toggleCheckboxChange = e => {
    cb1 === true ? setcb1(false) : setcb1(true);
  };
  const toggleCheckboxChange1 = e => {
    cb2 === true ? setcb2(false) : setcb2(true);
  };

  return (
    <div>
      <h3>CheckBox reusable component example</h3>
      <CheckBox
        id={"cb1"}
        value={"One"}
        isChecked={cb1}
        onclickHandler={toggleCheckboxChange}
      />
      <CheckBox
        id={"cb2"}
        value={"Two"}
        isChecked={cb2}
        onclickHandler={toggleCheckboxChange1}
      />
    </div>
  );
}
  • Open App.js file and update code as below
import React from 'react';
import CheckBoxEXP from './Components/CheckBoxEXP'

function App() {
  return (
    <div>
      <CheckBoxEXP/>
    </div>
  );
}

export default App;
Output:



No comments:

Post a Comment