evgkch evgkch - 1 year ago 110
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) {

this.state = {
selected: 0

handleClick(index) {
this.setState({ selected: index })

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

render() {
return (

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

<Tabs />,

<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 Source

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 () {
}, 1000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download