Denis Denis - 12 days ago 8
React JSX Question

React JS Toggle for showing additional info about contacts

I've just started to learn React and trying to implement toggle effect in Contacts list, that should show additional info about contact, when you click on it.

Current code is following:

var CONTACTS = [
{
id: 1,
name: 'Darth Vader',
phoneNumber: '+250966666666',
image: 'img/darth.gif',
email: 'vader@deathstar.com',
address: 'Death Star'
}, {
id: 2,
name: 'Princess Leia',
phoneNumber: '+250966344466',
image: 'img/leia.gif',
email: 'leia@skywalker.com',
address: 'Naboo'
}
];

var Contact = React.createClass({
getInitialState : function () {
return {
isOpened : false
};
},

toggleState : function () {
this.setState({
isOpened: !this.state.isOpened
});
},

render: function() {
return (
<li className="contact" onClick={this.toggleState}>
<img className="contact-image" src={this.props.image} width="60px" height="60px" />
<div className="contact-info">
<div className="contact-name"> {this.props.name} </div>
<div className="contact-number"> {this.props.phoneNumber} </div>
<div> {this.state.isOpened} </div>
</div>
</li>
);
}
});


How can I set isOpened equal to contact address and email to show it when toggle is triggered?
Thanks!

Answer

We can change

<div> {this.state.isOpened} </div>

to

{
    this.state.isOpened ?
        <div>
            <div className="contact-email"> {this.props.email} </div>
            <div className="contact-address"> {this.props.address} </div>
        </div>
        :
        null
}

What that does is show the divs with the email and address if this.state.isOpened is true. Otherwise returns null (an empty UI)

Then, you can change the state using a checkbox, toggle button or any other toggling control (which basically calls your toggleState method).

For example, using a checkbox (any where in your page):

<input type="checkbox" checked={this.state.isOpened} onChange={this.toggleState} />
Comments