4

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>
        );
    }
}
1
  • I updated my answer to fix your problem. Commented Oct 18, 2017 at 1:03

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Better would be to pass a function to setState to ensure that you are always working with the latest state: this.setState(state => this.setState({linksHidden: !state.linksHidden}));.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.