I have 2 buttons displayed on the page Display and Hide. When the Hide button is clicked I want to hide the Display button.
I am using useState. To some extent, I am able to hide Display more text present on the button, but not the whole button
Initial state- https://ibb.co/jMdH3tq
When the Hide button is clicked, Display text disappear but the button stays- https://ibb.co/Jm5FPNy
const [show, setShow] = useState(false);
const hideButton = () => {
setShow(true);
};
Hide button code:
<div>
<button
style={{ marginLeft: '190px' }}
className="button button1"
onClick={() => {
clearBooks();
hideButton();
}}
>
Hide
</button>
</div>;
Show button code:
<button
className="button button1"
style={{ marginLeft: '190px', width: '124px', height: '50px' }}
onClick={fetchBooks}
>
{!show && 'Display more'}
</button>;
If you are trying to hide the button do the following: I noticed the show state is set to false initially and you are setting it to true on click. Do you want the opposite, true as initial state hide when selecting the button?
Based on that, adjust show accordingly either show or !show
{show &&
<button
className="button button1"
style={{ marginLeft: "190px", width: "124px", height: "50px" }}
onClick={fetchBooks}
>
</button>
}
A tidier way of doing this would be to use the ternary operator with your state. Every time your buttons are clicked, they invert the state which changes which button is rendered in the DOM.
import { useState } from "react";
export default function App() {
const [show, setShow] = useState(true);
function changeState() {
setShow(!show);
}
return (
<div className="App">
{show ? (
<button onClick={changeState}> Display </button>
) : (
<button onClick={changeState}> Hide </button>
)}
</div>
);
}
If you don't want to re-render, you can achieve this by using classes as follows:
screen.js
import "./styles.css"
export default function MyScreen() {
const onButtonPressed = (target) => {
document.querySelector('button.hide').classList.remove('hide')
target.classList.add('hide')
}
return (
<div>
<button
style={{ marginLeft: 190 }}
className="button button1 hide"
onClick={(element) => {
onButtonPressed(element.target)
clearBooks()
}}
>
{"Hide"}
</button>
</div>
<div>
<button
className="button button1"
style={{ marginLeft: 190, width: 124, height: 50 }}
onClick={(element) => {
onButtonPressed(element.target)
fetchBooks()
}}
>
{"Display more"}
</button>
</div>
)
}
styles.css
button.hide {
display: none;
}
This is an example testing the JS functionality:
button.hide {
display: none;
}
<div>
<button
class="button button1 hide"
style="margin-left:190px;width:124px;height:50px"
onClick="onButtonPressed(this)"
>
Hide
</button>
</div>
<div>
<button
class="button button1"
style="margin-left:190px;width:124px;height:50px"
onClick="onButtonPressed(this)"
>
Display more
</button>
</div>
<script>
function onButtonPressed(element) {
document.querySelector('button.hide').classList.remove('hide')
element.classList.add('hide')
}
</script>