DEV Community

Ozan Yurtsever
Ozan Yurtsever

Posted on

2 1

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

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top 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?

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

If you found this article helpful, please give a ❤️ or share a friendly comment!

Got it