evgkch evgkch - 1 month ago 9
React JSX Question

React and render Tabs

So, I render tabs' titles by "renderTitles()". I need to get index of my tab when I clicked at the title and set it to "selected" prop. "handleClick()" displays current index - it's ok, but I don't understand why state of "selected" isn't the same as. Where I'm wrong?



const tabTitle = ['Prices', 'Description', 'Analytics'];

class Tabs extends React.Component {

constructor(props) {
super(props);

this.state = {
selected: 0
}
}

handleClick(index) {
this.setState({ selected: index })
console.log(this.state.selected)
console.log(index)
}

renderTitles() {
return tabTitle.map( (el, index) => {
return (
<li key={index}>
<a href="#"
onClick={this.handleClick.bind(this, index)}>
{el}
</a>
</li>
);
})
}

render() {
return (
<div>
<ul>{this.renderTitles()}</ul>
</div>
);
}
}

Tabs.propTypes = {
selected: React.PropTypes.number
}

ReactDOM.render(
<Tabs />,
document.getElementById('root')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>




Answer

this.setState is asynchronous. If you want to see what selected is set to, do so after a timeout:

this.setState({ selected: index })
setTimeout(function () {
  console.log(this.state.selected);
}, 1000);