user7597670
user7597670

Reputation:

add active class to selected item react

I have made a react parent component and if a user clicks on one of the two options a different child component is rendered.

Depending upon which option has been selected I want to add an active class.

See my code below.

I have taken many approaches but have stripped them off for the question as I could not figure it out.

class Test extends Component {

    constructor(props) {
        super(props);

        this.state = {
            currentView: 'one'
        };

        this.showOne = this.showOne.bind(this);
        this.showTwo = this.showTwo.bind(this);
    }

    showOne() {
        this.setState({
            currentView: 'one'
        });
    }

    showTwo() {
        this.setState({
            currentView: 'two'
        });
    }

    render(){
    ......
        <p className="one" onClick={this.showOne}>One</p>
        <p className="two" onClick={this.showTwo}>Two</p>
    ......
    }
}

Upvotes: 2

Views: 2717

Answers (1)

x-ray
x-ray

Reputation: 3329

Are you looking for something like this?

<p className={this.state.currentView === 'one' ? 'one active' : 'one'} onClick={this.showOne}>One</p>
<p className={this.state.currentView === 'two' ? 'two active' : 'two'} onClick={this.showTwo}>Two</p>

Upvotes: 1

Related Questions