0

I have react component like:

 class UserList extends Component {
      render() {
        const {users} = this.props
        users.forEach(function(user){
            console.log(user.name)
            if(user.photos){
                console.log(user.photos.data[0].source)
                return (
                    <div>
                        <p>{user.name}</p>
                    </div>
                )
            }
        })
      }
    }

    export default UserList

But it is giving me error saying should return valid react component but returned array or undefined..

The return function should return the component right ?

What am I missing here ??

1 Answer 1

2

As the error states you need to return a valid React element.

The fix is to return a DOM node from your render, a div for example.

class UserList extends Component {
    render() {
        return <div></div>;
    }
}

Further more using .forEach will not return a valid React element to the div, use .map instead to produce an array that you render.

class UserList extends Component {
    render() {
        return <div>{ 
            this.props.users
                .filter(user => user.photos)
                .map((user) => {
                    return <li>{ user.name }</li>;
            }}
        </div>;
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

The .filter will take care of that.
If no photos I dont want to display the name.. also photos contains images like photos[0] photos[1] so how to display them with name ?
The .filter will take care of seeing if you have any photos and displaying images is done as normal { user.photos[0].propertyOfImageObject }.
User which does not have photos is not displaying and giving error.. Each child in an array or iterator should have a unique "key" prop.
User without photos should not be displayed as per your if statement in your question. The error you're getting is easily read up in the React Docs. I'm not going to write your app for you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.