0

What I'm trying to achieve with this question is to not pass the <li> tag in the App.js component. The only solution I've found with the REACT documentation is to use an array and map it to <li> tag. The thing is that doing it this way is not so clean.

App.js

const App = () => {
  <Component>
    <li>
      <Link> Item 1 </Link>
    </li>
    <li>
      <Link> Item 2 </Link>
    </li>
    <li>
      <Link> Item 3 </Link>
    </li>
  </Component>
}

Component.js

const Component = ({children}) => {
  return(
    <ul>{children}</ul>
  )
}

Edit: My components where cluttered with unnecessary tags.

3
  • 1
    Shouldn't App.js start with const App = ? (twice) Commented Aug 8, 2021 at 23:52
  • 1
    I think you'll need to provide a clearer example for what you want. I don't think it's clear at all what you are asking for. If you are rendering an unordered list you'll need to render a list item (li) as a child, then you can render any child element/component from there. Commented Aug 8, 2021 at 23:53
  • I'll agree not clear. That being said, you may consider a react fragment <>stuff</> Commented Aug 8, 2021 at 23:55

1 Answer 1

1

You can use React.Children.map to make the <li> be added to each of the children, instead of making each child responsible to do it for themselves:

const App = () => {
  <Component>
    <Item />
    <Item />
  </Component>
}
const Component = ({children}) => {
  return(
    <ul>
      {React.Children.map(children, (child, i) => <li key={i}>{child}</li>)}
    </ul>
  )
}
Sign up to request clarification or add additional context in comments.

3 Comments

The children prop isn't an array, so you can't just map like this.
The comment of @DrewReese is correct. Nonetheless, there is a workaround to convert the children prop into an array. React.Children.map(children, (...))
Ah you're both right, it was late... now fixed.

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.