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;
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
</>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With