Ezeewei Ezeewei - 2 months ago 18
Javascript Question

ReactJS not able to reference state created

http://jsfiddle.net/adamchenwei/3rt0930z/20/

I just trying to create an example to learn how state works in a list.

What I intent to do is to allow a particular value that got repeated in a list, to change, in ALL items in the list, by using state. For example, in this case, I want to change all the list item's name to 'lalala' when I run

changeName
of onClick.

However I have this warning (issue at fiddle version 11, resolved at version 15)
enter image description here

Any help on resolving it to achieve purpose above?

Actual Code

var items = [
{ name: 'Believe In Allah', link: 'https://www.quran.com' },
{ name: 'Prayer', link: 'https://www.quran.com' },
{ name: 'Zakat', link: 'https://www.quran.com' },
{ name: 'Fasting', link: 'https://www.quran.com' },
{ name: 'Hajj', link: 'https://www.quran.com' },
];

var ItemModule = React.createClass({
getInitialState: function() {
return { newName: this.props.name }
},
changeName() {
console.log('changed name');
this.setState({ newName: 'lalala' });
},
render() {
//<!-- <a className='button' href={this.props.link}>{this.props.name}</a> -->
return (
<li onClick={this.changeName}>

{this.state.newName}
</li>
);
}
});

var RepeatModule = React.createClass({
getInitialState: function() {
return { items: [] }
},
render: function() {

var listItems = this.props.items.map(function(item) {
return (
<div>
<ItemModule
key={item.name}
name={item.name} />
</div>
);
});

return (
<div className='pure-menu'>
<h3>Islam Pillars</h3>
<ul>
{listItems}
</ul>
</div>
);
}
});

ReactDOM.render(<RepeatModule items={items} />,
document.getElementById('react-content'));


-UPDATE-
fiddle version 16

updated fidle, now there is issue with key, also, the onClick did not update the value for all the list item. Is there something wrong I did?

-UPDATE-
fiddle version 20

Now the only issue is
change all the list item's name to 'lalala' when I run changeName of onClick.

Answer

remove the parenthesis from

onClick={this.changeName()},

so

onClick={this.changeName}

you want to call the function onClick, but you are calling it on render that way