Reputation: 5924
I'm trying to create an accordion style button and have setup my component with the button functionality to hide my list on click, but I the list does not reappear and would also like to add an animated transition between hiding/showing the list. Should I be using prevState
in my handleClick()
function? Is there a preferred method for handling the animation? React? CSS?
//Render Links
const ReportLinks = props => {
return (
<ul>
{
props.links.map((link, index) => {
return ( <li key={index}><a href={link.reportLink}>{link.reportLink}</a></li> )
})
}
</ul>
)
}
class Footer extends React.Component {
constructor(props){
super(props);
this.state = { linksHidden: true };
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
this.setState({ linksHidden: false });
}
render() {
return (
<div className="annotation-card__footer">
<button onClick={this.handleClick}>Report Links ({this.props.report.length})</button>
{ this.state.linksHidden ? <ReportLinks links={this.props.report}/> : null }
</div>
);
}
}
Upvotes: 4
Views: 602
Reputation: 2193
I think I found your problem. In your handleClick method, you change the state to false to hide your list. When one presses the button again to show the list, all they are doing is setting the state to false again. Flip the state like this:
handleClick() {
this.setState({ linksHidden: !this.state.linksHidden });
}
EDIT: Felix Kling is correct. The code above is okay for simple applications, but when your app becomes more complex and setState can be called many times in a small amount of time it would be best to use a function as Felix Kling stated.
handleClick() {
this.setState(state => ({ ...state, linksHidden: !state.linksHidden }));
}
As for the animation, you could use CSS transitions. Just add or remove a class when the state changes. If you want more control, try using react-motion. I don't any experience with it, but it doesn't look too difficult to use.
Upvotes: 1