There's an array of react components inside parent component. On some event on parent component I'd like to run through the array of child components and call a method for each. How can I achieve that? It seems it doesn't work as in vanilla JS where you have an instance for the class and simply call a method. So here's the simplified code:
const Item = props => {
const value = () => 'result!';
return (
<div></div>
)
}
const App = props => {
const items = props.items.map(item => <Item key={uuid()} item={item} />)
const run = e => {
items.map(item => console.log(item.value()))
}
return (
<button onClick={run} type="button">Run!</button>
)
}
const items = [
'Lorem ipsum dolor sit amet',
'consectetur adipiscing elit'
];
ReactDOM.render(<App items={items} />, document.querySelector("#app"))
I've created a jsfiddle with this code - https://jsfiddle.net/jkLq26pg/37/
On the 11th string the method value() is called and it raises an error. But logging item.props works and outputs props for each item. Why methods are not called?
Please provide me with an advice how to make it work.
valuelike it's a class methoditem.value(), which it isn't. You're writing plain functions sovalueis only available within yourItemfunction.onChangeprop to communicate the changed value, and the parent then keeps the state of values.