mardi 16 juillet 2019

How to change checkbox in react correctly?

What is the correct way to change checkbox value?

option 1

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [x, setX] = useState(false);

  const soldCheckbox = ({ target: { checked } }) => {
    console.log(x, checked);
    setX(checked);
  };
  return (
    <div>
      <input type="checkbox" checked={x} onChange={soldCheckbox} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

option 2

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [x, setX] = useState(false);
  console.log(x);
  return (
    <div>
      <input type="checkbox" checked={x} onChange={() => setX(!x)} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

In fact, I think there's no difference, but I just wanted to hear a different opinion. Maybe something I do not know or there may be other solutions to this problem.




Aucun commentaire:

Enregistrer un commentaire