Reputation: 6806
This is really driving me in nuts. I wrote so many components and this is so basic, but probably there is something that I can't realize in this simple scenario. Basically my render is not being updated when I set the state.
import React, {Component} from 'react'
import styles from './styles'
import {css} from 'aphrodite'
export class Switcher1 extends Component {
constructor(props) {
super(props)
this.state = {
selected: 0
}
}
setIndex(ndx) {
console.log(ndx)
this.setState = {selected: ndx}
}
render() {
console.log('Rendering...')
const sel = this.state.selected
return (
<div className={css(styles.container)}>
{this.props.options.map((item, index) => {
const isSelected = index === sel
return <div key={index}
className={isSelected ? css(styles.active) : css(styles.notActive)}
onClick={() => this.setIndex(index)}>
<img className={css(styles.image)}
src={"/assets/images/" + item.icon + (isSelected ? '_blue.svg' : '_white.svg')}/>
{item.text} - {sel} - {index} - {isSelected.toString()}
</div>
})}
</div>)
}
}
Updated code...but it's still not works...
import React, {Component} from 'react'
import styles from './styles'
import {css} from 'aphrodite'
export class Switcher1 extends Component {
constructor(props) {
super(props)
this.state = {
selected: 0
}
this.setIndex = this.setIndex.bind(this)
}
setIndex(ndx) {
console.log(this.state)
this.setState = ({selected: ndx})
}
render() {
console.log('Rendering...')
const sel = this.state.selected
return (
<div className={css(styles.container)}>
{this.props.options.map((item, index) => {
const isSelected = index === sel
return <div key={index}
className={isSelected ? css(styles.active) : css(styles.notActive)}
onClick={() => this.setIndex(index)}>
<img className={css(styles.image)}
src={"/assets/images/" + item.icon + (isSelected ? '_blue.svg' : '_white.svg')}/>
{item.text} - {sel} - {index} - {isSelected.toString()}
</div>
})}
</div>)
}
}
Any thoughts ?
Upvotes: 0
Views: 45
Reputation: 1416
1) You forgot to bind this to your setIndex method : setIndex=(ndx)=> {
2) the setState is wrong, replace by : this.setState({ selected: ndx });
result :
setIndex = (ndx) => {
console.log(ndx);
this.setState({ selected: ndx });
}
Upvotes: 3
Reputation: 17269
You have:
this.setState = {selected: ndx}
This is not how you set state. Try this:
this.setState({ selected: ndx });
Also, as @benjamin mentioned, you should bing the setIndex
function by using an arrow function:
setIndex = () => { ... }
or binding in your constructor:
this.setIndex = this.setIndex.bind(this);
You can read the docs on setState
here.
Upvotes: 2