Erik Åstrand Erik Åstrand - 3 months ago 25
React JSX Question

ReactJS - Target random element

I have some problems understanding how you interact with element in React after rendering. I currently got this fiddle: https://jsfiddle.net/y7dh3vh5/

var items = ["Afghanistan","Albania","Algeria","Andorra","Angola"....

var RepeatModule = React.createClass({
getDefaultProps: function() {
return { items: [] }
},
render: function() {
var listItems = this.props.items.map(function(item, i) {
return (
<div className="item" key={i}>
<p>{item}</p>
</div>
);
});

return (
<div>
{listItems}
</div>
);
}});ReactDOM.render(<RepeatModule items={items} />, document.getElementById('itemList'));


And I'm looking for a way to highlight a random country when I press the "Highlight random country"-button. Is there an easy way to implement this?

Thanks in advance.

Answer

Add state to save highlightedIndex:

getInitialState () {
    return {
        highlightedIndex: -1
    }
},

Add method for button

setNewTarget: function() {
    var l = this.props.items.length - 1;
    this.setState({
        highlightedIndex: this.randomInteger(0, l)
    })
},

Put button into return render

return (
    <div>
        <button onClick={this.setNewTarget}>
            Highlight random country
        </button>
        {listItems}
    </div>
);

Live example: https://jsfiddle.net/ufmagg4o/