Home > Software engineering >  How to get data in reactjs when we select checkbox without reloading?
How to get data in reactjs when we select checkbox without reloading?

Time:08-16

I am trying to make an project in which data loads when we click on the checkbox in reactjs , for example we have this :

<h1> Please select an type </h1>
<input type="checkbox" id="Bike" name="Bike" value="Bike" />
<input type="checkbox" id="car" name="car" value="car" />

And then when we select the bike checkbox, our component loads and shows items from JSON file that only contains bikes without reloading or clicking the submit button Just like how we search on the react-icon website where we type our input and icons load without reloading the whole page or clicking the submit button, thanks :)

CodePudding user response:

this is a simple sample.

const TestCheckBox = () => {
  const [carvalue, setCarValue] = useState(false);
  const [Bikevalue, setBikeValue] = useState(false);

  return (
    <>
      <h1> Please select an type </h1>
      <input
        type="checkbox"
        onChange={({ target }) => setBikeValue(target.checked)}
        id="Bike"
        name="Bike"
        value="Bike"
      />
      <label>{Bikevalue ? "bike Checked" : "bike Unchecked"}</label>
      <div>
        <input
        type="checkbox"
        onChange={({ target }) => setCarValue(target.checked)}
        id="car"
        name="car"
        value="car"
      />
        <label>{carvalue ? "Car Checked" : "Car Unchecked"}</label>
      </div>
    </>
  );
};

You can use this method

const [value, setValue] = useState({});

const checkHandle=({target})=>{
   let temp={...value,
       [target.name]:target.checked
       };
  }

CodePudding user response:

whenever there is a change in your checkbox function

e.target.value will give you the selected data

handleChange = (e) => {
      this.setState({
        [e.target.name]: e.target.value,
      });
    }

You can create a custom onChange function :

<input
  type="checkbox"
  name="check"
  checked={this.state.check}
  onChange={(e) => {
    this.handleChange({
      target: {
        name: e.target.name,
        value: e.target.checked,
      },
    });
  }}
/>

CodePudding user response:

(In this example I've used radio buttons to simplify things.)

When the checked status of a button is changed call an event handler. This updates the radio button status, and then calls the API with the button id. The API sends back the relevant data, and the handler updates the data state with that.

When the state changes (the state array has length > 0) create a table using the data in state.

const { useState } = React;

// Sample data
const data={bike:[{id:1,name:"Bike1",type:"Type1"},{id:2,name:"Bike2",type:"Type2"}],car:[{id:1,name:"Car1",type:"Car1"},{id:2,name:"Car2",type:"Car2"}]};

// Mock API that sends data based on the
// id it's passed after two seconds
function mockApi(id) {
  return new Promise(res => {
    setTimeout(() => {
      res(JSON.stringify(data[id]));
    }, 2000);
  });
}

function Example() {

  // Two states: one to hold the button status, the
  // other to hold the data
  const [ radio, setRadio ] = useState({});
  const [ data, setData ] = useState([]);

  // Destructure the id from the button dataset,
  // set the button state, and then get the data using
  // that id. When the data is returned update the data state
  function handleChange(e) {
    const { id } = e.target.dataset;
    setRadio(id);
    mockApi(id)
      .then(res => JSON.parse(res))
      .then(setData);
  }

  // Create an array of cell data
  function createCells(obj) {
    return Object.values(obj).map(value => {
      return <td>{value}</td>;
    });
  }

  // Create an array of rows
  function createRows(data) {
    return data.map(obj => {
      return <tr>{createCells(obj)}</tr>;
    });
  }

  // Add some Radio components, and a table
  // When the data state is changed, and the state
  // contains some data, create a table
  return (
    <div>
      <div>
        <Radio
          id="car"
          name="radio"
          checked={radio === 'car'}
          handleChange={handleChange}
        />
        <Radio
          id="bike"
          name="radio"
          checked={radio === 'bike'}
          handleChange={handleChange}
        />
      </div>
      <div className="output">
        {data.length
          ? (
            <table>
              <thead>
                <td>#</td>
                <td>Name</td>
                <td>Type</td>
              </thead>
              <tbody>{createRows(data)}</tbody>
            </table>
          )
          : 'No data'}
      </div>
    </div>
  );

}

// Returns a Radio component
function Radio({ id, checked, handleChange }) {
  return (
    <label>
      <span>{id}</span>
      <input
        type="radio"
        data-id={id}
        checked={checked}
        onChange={handleChange}
      />
    </label>
  );
}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
[type="radio"]:hover { cursor: pointer; }
.output { margin-top: 1em; }
label span { text-transform: uppercase; }
table { border-collapse: collapse; }
thead { background-color: #343434; color: white; }
td { padding: 0.25em 0.5em; border: 1px solid darkgray; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

  • Related