1

I have this component with some menu. In here there is some array iteration of menu items. I want to import this component to other main one but i'm receiving this error - A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.. When i'm remove this array iteration and leave simple link everything is fine. What is wrong?

component:

const LandingMenu = (props) => {
    return (
        props.data.map((element, _) =>
            <Link class="link" href={ element.target }>{ element.name }</Link>
        )
    )
};

export default LandingMenu;

import

<LandingMenu data={LANDING_CONTENT.menu} />
1
  • Tack on join("") ? Commented Oct 25, 2016 at 20:58

2 Answers 2

4

A React component cannot return an array... it has to return a single element.

Wrapping your output in a DIV would likely work fine:

const LandingMenu = (props) => {
    return (
        <div>
            {props.data.map((element, _) =>
                <Link class="link" href={ element.target }>{ element.name }</Link>
            )}
        </div>
    )
};

export default LandingMenu;
Sign up to request clarification or add additional context in comments.

Comments

2

Components need to be wrapped in a root element. Your notation would be fine if it was a helper function in a different class.

So your LandingMenu needs to look like this:

return (
    <div>
        {props.data.map((element, _) =>
            <Link class="link" href={ element.target }>{ element.name }</Link>}
    </div>
    )
)

an alternative solution would be to have a render helper function inside whatever component is currently using LandingMenu

//SomeComponent
renderHelperFunction(data){
    return (
        {data.map((element, _) =>
            <Link class="link" href={ element.target }>{ element.name }</Link>}
    )
)

render(){
    return (...

          {this.renderHelperFunction(this.props.data)}

    ...)
}

Comments

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.