How can I target a different react element inside the same component when I click on a button and how can this work when I reuse the component several times in my App.js?
I have created a react component that has a div and a button. By default, I made the div hidden by creating a "hidden" CSS style and giving the div the class "hidden". Now what I want to achieve is that when I click the button, it will call a function that will make the div become visible by removing the hidden class from it's classList. My react component was created with class and I am binding the "this" keyword in constructor.
Now I have gone ahead to call the re-usable component above in four places in my App.js. On the first instance of the component, when I click the button, the div becomes visible as expected, but in other instances, when I click the buttons, the other corresponding divs do not become visible as expected per component instance. So my button click only affect the first instance of my react component while the remaining do not act accordingly.
This is the function I am calling by clicking the button
handleFinish() {
console.log("CLickedddd");
const editBtn = document.querySelectorAll(".ResetButton");
for (let i = 0; i < editBtn.length; i++) {
editBtn[i].classList.remove("hidden");
}
This is the button and div:
<button id="finish" onClick={this.handleFinish}>
Finish
</button>
<div style={{height: 300, width: 300, backgroundColor: "red"}} class="hidden">
</div>
You should use a state variable to control your div's visibility.
class App extends Component {
constructor() {
super();
this.state = { hidden: false };
}
handleFinish = () => {
console.log("CLickedddd");
this.setState({ hidden: !this.state.hidden });
};
render() {
return (
<>
<button id="finish" onClick={this.handleFinish}>
Finish
</button>
<div
style={{ height: 300, width: 300, backgroundColor: "red" }}
className={this.state.hidden ? "hidden" : ""}
></div>
</>
);
}
}
See this sandbox
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments