I have a code that disables a button when clicking on it, this works, but it's disabling all the buttons I have on the screen.
This is the part of code, I'm using class components:
constructor(props) {
super(props);
this.state = { isLoading: false };
}
handleFile(file) {
const id = file.id; // maybe I can use this id?
this.setState({ isLoading: true });
if (document.statusCode == 200) {
this.setState({ isLoading: false });
}
}
_renderButton(text, props) {
const isFile = (props.type.toLowerCase() === 'file');
return (
<Row>
{isFile && (
<Button disabled={this.state.isLoading} onClick={(e) => { e.stopPropagation(); this.handleFile(props)}} />
)}
</Row>
);
}
How can I disable just the clicked button using react? How to use the map in this situation?
Give each button an id data attribute and use state to register whether that button has been clicked, and if it has disable it on the next render.
const { Component } = React;
class Example extends Component {
constructor() {
super();
this.state = {};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
const { id } = e.target.dataset;
this.setState({ ...this.state, [id]: true });
}
createButtons() {
const jsx = [];
for (let i = 0; i < 10; i++) {
const button = <button
data-id={i}
disabled={this.state[i]}
onClick={this.handleClick}
>Click me {i}
</button>;
jsx.push(button);
}
return jsx;
}
render() {
return (
<div>
{this.createButtons()}
</div>
);
}
}
ReactDOM.render(
<Example />,
document.getElementById("react")
);
button:disabled { color: red; opacity: 50%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>