Beginnerprogrammer Beginnerprogrammer - 2 months ago 20
React JSX Question

ReactJS Different Classes

Iam new to ReactJS and I am working on a filterable gallery but now Iam looking at an example of thinking in ReactJS and I saw that they are building different classes for each component. I didn't do that but now Iam trying to do this, First my code looked like this: `

var SearchBar = React.createClass({
getInitialState() {
return { text:'', array: this.props.array};
},
handleChange(event) {
var array = this.filterList(event.target.value);
this.setState({ text: event.target.value, array: array });

return this.state.text;
},
render() {
var arrayComponents = this.state.array.map(function(photo) {
return <li className="photo photo-name">{photo.name} <img className="photo" src={photo.link}/></li>;
});

return <div>
<h1>Hello, {this.props.name}</h1>
<p>{this.state.text}</p>
<input type="text" onChange={this.handleChange} />
<ul>
{arrayComponents}
</ul>
</div>;
},
filterList (filterText) {
var updatedList = this.props.array,
filterTextLength = filterText.length;

return updatedList.filter(function(item){
var splitName = item.name.toLowerCase().slice(0, filterTextLength);
var lowerCaseFilterText = filterText.toLowerCase();
return splitName === lowerCaseFilterText;
});
}
});


Now I want to create an other Class of ImageList which has to include the
var arrayComponents
but if i do this:

var ImageList = React.createClass({
render() {
var arrayComponents = this.props.array.map(function(photo) {
return <li className="photo photo-name">{photo.name} <img className="photo" src={photo.link}/></li>;
});
<ul>
{arrayComponents}
</ul>
}
})


and than in the render function add
<ImageList array={array}/>
instead of
<ul>{arrayComponent}</ul>
it throws me the error that
Cannot read property 'map' of undefined
How do I pass the state of array into that ImageList class.

Here is a codepen: LINK

Answer

I've made the following changes in your code: http://codepen.io/PiotrBerebecki/pen/zKRAGZ

1) Pass the state of array into that ImageList class

<ImageList array={this.state.array} />

2) Add a return statement in the render method of ImageList

// Add return
    return (
      <ul>
        {arrayComponents}
      </ul>
    );

3) Add key attribute to the li tag when using map method:

      var arrayComponents = this.props.array.map(function(photo, index) {
// -------------------------------
// Add index to the li tag
// ----------------vvvvvvvvvvv
        return <li key={index} className="photo photo-name">{photo.name} <img className="photo" src={photo.link}/></li>;
      });

React Docs: https://facebook.github.io/react/docs/multiple-components.html#dynamic-children