0

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>
evgkch
  • 637
  • 1
  • 5
  • 7

1 Answers1

0

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);
Community
  • 1
  • 1
Sal Rahman
  • 4,607
  • 2
  • 30
  • 43
  • Yes, you are right, thank you!
    {this.state.selected}
    is ok!
    – evgkch Nov 04 '16 at 19:31
  • I might also point out, that the *new* value of `this.state` is implicitly known at each `render`. Therefore, debugging the new value of `this.state` at the subroutine where `this.setState` is called is almost redundant, unless you are more or less certain that there is a bug in React itself, or some library that interacts with React (if it's the latter, then stop using that library, IMNSHO). – Sal Rahman Nov 04 '16 at 21:45