Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to hide and show input conditionally in React Js

I Know this approach is not good in react js. but i don't know how to achieve same with react js. not getting the right way of doing this. I have multiple input which I have to hide and show based on value selected from dropdown.

I am making this demo code for anyone who want to check. https://codesandbox.io/s/gracious-hertz-k2ttl8?file=/src/App.js:0-1084

App.js

const App = () => {
  const getInput = (e) => {
    let input = e.target.value;
    let data = document.getElementsByClassName(input);
    data.array.forEach((ele) => {
      if (ele.style.display === "none") {
        ele.style.display = "block";
      }
    });
  };
  return (
    <>
      <select onChange={getInput}>
        <option value="Address">Address</option>
        <option value="Name">Name</option>
        <option value="Both">Name && Address</option>
      </select>
      <br />
      <br />

      <input
        className="Address Both"
        type="text"
        name="city"
        placeholder="City"
      />
      <input
        className="Address Both"
        type="text"
        name="pincode"
        placeholder="pincode"
      />

      <br />
      <br />
      <input
        className="Name Both"
        type="text"
        name="firstName"
        placeholder="First Name"
      />
      <input
        className="Name Both"
        type="text"
        name="firstName"
        placeholder="Last Name"
      />
    </>
  );
};

export default App;
like image 725
Kuldeep Singh Avatar asked Dec 21 '25 17:12

Kuldeep Singh


1 Answers

You can use a state to store the selected value and then render the input based on that state:

const App = () => {
  const [selected, setSelected] = useState("");

  const getInput = (e) => {
    setSelected(e.target.value);
  };
  return (
    <>
      <select onChange={getInput}>
        <option value="Address">Address</option>
        <option value="Name">Name</option>
        <option value="Both">Name && Address</option>
      </select>
      <br />
      <br />

      {selected === 'Address'&&<input
        className="Address Both"
        type="text"
        name="city"
        placeholder="City"
      />}
      // Similarly for the other inputs
    </>
  );
};
like image 198
nullptr Avatar answered Dec 23 '25 10:12

nullptr