DEV Community 👩‍💻👨‍💻

Ozan Yurtsever
Ozan Yurtsever

Posted on

Custom React Hook to Check Nested Child Component Types

A component may want to make assumptions about its children to satisfy layout constraints. This custom hook helps you to determine if there is any nested child with a specific type, and returns you the nested child itself to apply any layout constraints to it while rendering.

Usage

import useChild from 'use-child';

const Car = props => {
  const [wheelExists, WheelComponent] = useChild(props.children, Wheel);
  const [engineExists, EngineComponent] = useChild(props.children, Engine);

  return (
    <div>
      {wheelExists && WheelComponent}
      {engineExists && EngineComponent}
    </div>
  );
};

const Wheel = () => {
  return <div>I am a wheel</div>;
};

const Engine = () => {
  return <div>I am an engine</div>;
};
Enter fullscreen mode Exit fullscreen mode

GitHub logo ozanyurtsever / use-child

A custom react hook to check nested child component types

use-child

React hook for getting the type of any nested child component

A component may want to make assumptions about its children to satisfy layout constraints. This custom hook helps you to determine if there is any nested child with a specific type, and returns you the nested child itself to apply any layout constraints to it while rendering.

Install

npm install use-child
Enter fullscreen mode Exit fullscreen mode

Usage

import useChild from 'use-child';
const Car = props => {
  const [wheelExists, WheelComponent] = useChild(props.children, Wheel);
  const [engineExists, EngineComponent] = useChild(props.children, Engine);

  return (
    <div>
      {wheelExists && WheelComponent}
      {engineExists && EngineComponent}
    </div>
  );
};

const Wheel = () => {
  return <div>I am a wheel</div>;
Enter fullscreen mode Exit fullscreen mode

Latest comments (1)

Collapse
 
brense profile image
Rense Bakker

Will it work also with multiple children of the same type like in a select -> options scenario?

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠