I was wondering if it's possible to manipulate multiple things in a component when a button is clicked.
At the moment I have a simple component. When the button is clicked it adds an id to an array... pretty simple stuff.
But what I want to also do when the button is pressed is change the button text to 'Selected' and add the 'color="danger"' tag to the button.
I'm finding this really difficult. Any help would be greatly appreciated.
import React, { Component } from "react";
import { Col, Card, CardBody, Button } from "reactstrap";
class ThisComponent extends Component {
addResponse(id) {
this.props.addResponseInState(id);
}
render() {
const { id } = this.props;
return (
<Col>
<Card>
<CardBody>
<Button onClick={() => this.addResponse(id)}>Select</Button>
</CardBody>
</Card>
</Col>
)
}
}
export default ThisComponent;
You should get familiar with using component-state, which is the bread and butter of React.
State essentially helps you keep track of the component at all times, be it some sort of status or some data you want to maintain.
import React, { Component } from "react";
import { Col, Card, CardBody, Button } from "reactstrap";
class ThisComponent extends Component {
state = {
clicked: false
}
addResponse(id) {
this.props.addResponseInState(id);
this.setState({
clicked: true
})
}
render() {
const { id } = this.props;
return (
<Col>
<Card>
<CardBody>
<Button
color={this.state.clicked ? "danger" : ""}
onClick={() => this.addResponse(id)}
>
{ !this.state.clicked ? "Select" : "Selected"}
</Button>
</CardBody>
</Card>
</Col>
)
}
}
export default ThisComponent;
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