user8826104
user8826104

Reputation:

React - How to change material icon with an onClick event?

I'm trying to change the material icon from add to remove with an on click event in React. To clear up some confusion, this has nothing to do with classes, it's to do with the material icon that actually displays. Add is a plus icon, I need to change it from add to remove, which is a subtract icon.

handleClick() {
    console.log('test');    
}

render() {
    <div>
        <i className="material-icons mobile" onClick={(e) => this.handleClick(e)}>add</i>
    </div> 
}

The above works console outputs test perfectly fine, I just have no idea how to approach this. Done some research online and can't find anything about this. Could use with some insight or ideas for an approach to this.

Upvotes: 0

Views: 7354

Answers (2)

Stretch0
Stretch0

Reputation: 9241

You can do that by setting state. Something like this:

state = { icon: true }

handleClick = e => {
    const { icon } = this.state
    this.setState({ icon: !icon })   
}

render() {
    const { icon } = this.state
    return(
        <i className='large material-icons' onClick={this.handleClick}>
            { icon ? 'add' : 'remove'}
        </i>
    )

}

Upvotes: 0

Yair Rodr&#237;guez
Yair Rodr&#237;guez

Reputation: 53

Improving the last answer:

constructor() {
    super();
    this.state = { icon: true };
}

handleClick() {
    this.setState({ icon: !this.state.icon })   
}

render() {
    <i className='large material-icons' onClick={(e) => this.handleClick(e)}>
        { this.state.icon ? 'add' : 'remove' }
    </i>
}

Upvotes: 1

Related Questions