Lalablala
Lalablala

Reputation: 77

Map over children with top level React Children API

I am trying to render the children in a component by mapping over the children with the React Children API.

I can't figure out why but the children are not renderen

import React from "react";
import List from "components/List";

function Artists(): JSX.Element {
  return (
    <List>
      <p key={"1"}> test1</p>
      <p key={"2"}>test2</p>
      <p key={"3"}>test3</p>
      <p key={"4"}>test4</p>
      <p key={"5"}>test5</p>
    </List>
  );
}

export default Artists;
import React, { Children } from "react";
interface List {
  children: JSX.Element[] | null;
}

function List(props: List): JSX.Element {
  const { children } = props;

  return (
    <ul>
      {Children.map(children, (child, i) => {
        <li key={i}>{child}</li>;
      })}
    </ul>
  );
}

export default List;

When I render the children outside the map function they are being rendered

import React from "react";
interface List {
  children: JSX.Element[] | null;
}

function List(props: List): JSX.Element {
  const { children } = props;

  return (
    <ul>
      <li>{children}</li>;
    </ul>
  );
}

export default List;

Can someone point in the direction what I am missing?

Upvotes: 0

Views: 1793

Answers (2)

Muteeullah jan
Muteeullah jan

Reputation: 1

Here you are writing C capital of children while destrucring props c of children is in small

Upvotes: 0

Alexander Sakhatskii
Alexander Sakhatskii

Reputation: 703

I suppose you should return child here

{Children.map(children, (child, i) => {
        <li key={i}>{child}</li>;
      })}
{Children.map(children, (child, i) => {
        return <li key={i}>{child}</li>;
      })}

Upvotes: 1

Related Questions