1

Im trying to dynamically print a lot of components into a li list.

In the parent component, the list menuLinks is an array. Each child of menuLinks is a component (LinkToChangePassword is a react functional component):

export default class Header extends Component{
  constructor(props){
    super( props );
  }

  render(){
    const menuLinks = [
      LinkToChangePassword,
      LinkToResetPassword,
      LinkToChangeEmail,
      LinkToLogOut
    ];
    return(
      <div className="header">
        <LinkToHome classAttr=""/>
        <h1 className="">{ this.props.heading }</h1>
        <DropDownMenu links = { menuLinks }/>
      </div>
    );
  }
}

In my child component, I'd like to attach these components:

export default class DropDownMenu extends Component{
  constructor( props ){
    super( props );
  }

  render(){
    let renderMenuItems = this.props.links.map(
      ( item, i ) => <li className = "menuItem"
                         key = {`li${i}`}>
                         {item}
                     </li>
    );
    return <ul className = "profileMenu">
            { renderMenuItems }
          </ul>;
  }
}

However, this doesnt work & I get empty list.

0

2 Answers 2

3

Try this once. Maybe this can help.

 const menuLinks = [
  <LinkToChangePassword />,
  <LinkToResetPassword />,
  <LinkToChangeEmail />,
  <LinkToLogOut />
];

Here is a fiddle https://jsfiddle.net/jwm6k66c/1785/

Sign up to request clarification or add additional context in comments.

Comments

2

Your trying to reference a react component by name only in JSX without surrounding it with angled brackets:

ComponentNameHere instead of: <ComponentNameHere>

One solution:

You'll need to ensure you are importing you components into you DropDownMenu class.

You can then replace {item} statement within your .map call to use React.createElement()

{React.createElement(item, null)}

Amended render function:

render(){
  let renderMenuItems = this.props.links.map( ( item, i ) => 
    <li className = "menuItem" key = {`li${i}`}>
      {React.createElement(item, null)}
   </li>
  ); 
  return <ul className = "profileMenu"> { renderMenuItems } </ul>;
}

1 Comment

They may be made but to use them within JSX you need to call them with angled brackets. I have not found a way to do this dynamically via JSX, but since JSX is just syntactic sugar for methods like React.cresteRlement, using it in your call as I stated above will work

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.