skip to Main Content

I have a <FakeItem> component that returns 2 components, title and content.

In the parent component <Index> I need it to separate those two components and render them separately.

This is a simplified example of my problem:

import { useId } from "react";

function FakeItem(props) {
  const id = useId();

  return (
    <>
      <a href={"#" + id}>{props.title}</a>
      <div id={id}>{props.content}</div>
    </>
  );
}

function Indice(props) {
  let FakeChild = props.children;

  // I already tried it...
  // FakeChild = <FakeChild />

  // I need to separate the child return (<FakeItem>)...
  const titulos = FakeChild[0]; // get <a>
  const conteudos = FakeChild[1]; // get <div>

  // They will be rendered separately
  return (
    <>
      <div className="titulos">{titulos}</div>
      <div className="conteudos">{conteudos}</div>
    </>
  );
}

export default function App() {
  return (
    <Indice>
      <FakeItem title="Intro" content="Once upon a time..." />
    </Indice>
  );
}

2

Answers


  1. You need to separate your FakeItem into 2 different components.

    Login or Signup to reply.
  2. props.children prepresents the elements that where wrapped with the component so in your example :

    <Indice>
       <FakeItem title="Intro" content="Once upon a time..." />
    </Indice>
    

    since there is only one element within <Indice>
    props.children in <Indice> component is not an array but an object.

    However In this example it is an array

    <Indice>
       <FakeItem title="Intro" content="Once upon a time..." />
       <FakeItem title="Intro2" content="Once upon a time2..." />
    </Indice>
    

    So props.children in your example is in fact the <FakeItem/> component so you still can access to its props :

    const childProps = props.children.props // {title: 'Intro', content: 'Once upon a time...'}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search