77
84

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React / Next】引数ありのComponent自体をpropsで渡して、子Component側で引数を渡したい

Last updated at Posted at 2022-06-19

個人的な備忘録です。

やりたいこと

  • 親から Component を渡す時には、引数なしで子へ渡す
  • 子Component側に props で渡ってきた component へ引数を渡す

環境

  • React: 17.0.2
  • Next: 11.1.3

サンプルコード

親Component

import { Item } from './components/item';

export const ParentComponent = () => {
  return (
    <>
      {/* Componentを()をつけずに渡す。引数なしの場合は()でもOK */}
      <ChildContainer component={item} />
    </>
  );
};

子Component

interface Props {
  component: (hoge: Hoge) => ReactNode;
  // 引数をオブジェクトにしている場合
  // component: (_props: {data: Data, Foo: string}) => ReactNode;
}

export const ChildContainer = ({ component }: Props) => {
  // 省略

  return (
	<Box>
      {data && data.map((item) => component(item))}
    </Box>
  )
}

Propsで渡されるComponent

export const Item = (hoge: Hoge) => {
  // 省略

  return (
    <div>
      <p>{date.title}</p>
    </div>
  );
};
77
84
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
77
84

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?