I have tried and require to be able to hide and show the test field with the click of the button in the code. I have tried other ways but i need to be able to do it with the code starting with const About...
const About = () => {
return (
<div>
<center>
<hr/>
<button>Show and hide element</button>
{
<div style={{ marginTop: "100px" }}>
<form
style={{
margin: "auto",
padding: "15px",
maxWidth: "400px",
alignContent: "center",
}}
>
<label htmlFor="Test">Test</label>
<input
type="text"
id="test"
name="test"
/>
</form>
</div>
}
</center>
</div>
);
};
ReactDOM.render(
<div>
DEMO
<About />
</div>,
document.getElementById("rd")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="rd" />
CodePudding user response:
You can use react hook useState and set states as show/hide and update the state when you click the button and use conditional rendering to show or hide the element using state.
CodePudding user response:
You can just toggle it using state:
Check useState
line and conditional rendering with show &&
.
(working example here )
const {useState, useEffect} = React;
const About = () => {
const [show, setShow] = useState(true)
return (
<div>
<center>
<hr/>
<button onClick={()=>setShow(!show)}>Show and hide element</button>
{
show &&
<div>
<form
style={{
margin: "auto",
padding: "15px",
maxWidth: "400px",
alignContent: "center",
}}
>
<label htmlFor="Test">Test</label>
<input
type="text"
id="test"
name="test"
/>
</form>
</div>
}
</center>
</div>
);
};
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<About/>)
CodePudding user response:
import React, { useState } from "react";
export default function About() {
const [hide, setHide] = useState(false);
return (
<div>
<button onClick={() => setHide(!hide)}>Show and hide element</button>
{!hide && <p>hide me</p>}{" "}
</div>
);
}