Gaurang Dhorda
Gaurang Dhorda

Reputation: 3387

React functional component not redering inside parent functional component

For reference, I have this StackBlitz Link . You can check output there not working.

I have one TodoList Line Item component and I want to render LineItem component inside of TodoListLineItem component. I am Using react with functional components and hooks with typescript.

<div className="container">
      <TodoForm />
      <TodoListLineItem>
          <LineItem />
      </TodoListLineItem>
</div>

As, shown above when i am trying to put <LineItem /> component inside of <TodoListLineItem> then, LineItem component is not rendering inside of parent component.

My Question is how to render LineItem component inside of parent TodoListLineItem component?

Upvotes: 0

Views: 839

Answers (1)

Yousaf
Yousaf

Reputation: 29282

LineItem component is a child of TodoListLineItem component. You need to render LineItem component inside TodoListLineItem component in order to render LineItem component.

When you nest a component like LineItem is nested inside TodoListLineItem component, that nested component is passed as a prop to the surrounding component and is accessible inside the surrounding component using children property on the props object.

props.children will be an array that contains all the children components of TodoListLineItem component. You can render all the children of TodoListLineItem by rendering props.children in TodoListLineItem component

const TodoListLineItem: React.FC = (props) =>{
   const [close, setClose] = useState(false);

   return (
     <div>
       <label className="line-item-header"> All Todo List items </label>
       { props.children }       {/* render all the children of TodoListLineItem */}
     </div>
   );
}

Demo

https://stackblitz.com/edit/react-ts-asvv7x

You can learn about props.children on React Docs - Composition vs Inheritance

Upvotes: 2

Related Questions