I'm new to React and trying to figure out how to keep a button highlighted when clicked. The desired behavior would be like a form, where the user is asked a question, and can choose multiple answers to submit. Each answer (button) clicked would remain highlighted. Is there a way to achieve this effect?
<>
<Stack gap={2} className="col-md-5 mx-auto">
<h1>Question to ask user ?</h1>
<br />
<Button>Option 1</Button>
<Button>Option 2</Button>
<Button>Option 3</Button>
<Button>Option 4</Button>
<Button>Option 5</Button>
</Stack>
</>
CodePudding user response:
I think you might be interested in something like the top answer for this post: How to keep :active css style after click a button. I think the JS answer they provided is what you're looking for, just don't include the remove class part.
CodePudding user response:
Create the new component extending the Button and assign the state in it.
class NewButton extends React.Component {
constructor(props) {
super(props);
this.state = {
selected: null
}
}
buttonSelected = selected => ev => {
this.setState({ selected })
}
render() {
return (
<Button className={key === this.state.selected ? 'selected' : ''}>
{this.props}
<Button>
);
}
}
CodePudding user response:
If you just want to hightlight a button based when clicked you can use css selectors like :visited
and :active
depending upon the situation.
But what you are asking for requires something else, maybe you can use checkbox for this or you can use this
class Form extends React.Component {
state = {
selected: [],
};
selectButton = (name) => {
const tempSelected = { ...this.state.selected };
tempSelected.push(name);
this.setState({ selected: tempSelected });
};
isSelected = (name) => {
return this.state.selected.includes(name);
};
render() {
return (
<>
<button onClick={(e) => selectButton("A")} className={this.isSelected("A") ? "selected" : ""}>
A
</button>
<button onClick={(e) => selectButton("B")} className={this.isSelected("B") ? "selected" : ""}>
B
</button>
<button onClick={(e) => selectButton("C")} className={this.isSelected("C") ? "selected" : ""}>
C
</button>
<button onClick={(e) => selectButton("D")} className={this.isSelected("D") ? "selected" : ""}>
D
</button>
</>
);
}
}