How to use children with React Stateless Functional Component in TypeScript
Using children prop
In React, the children prop allows you to pass components or elements as children to another component. In TypeScript, you can define the type of the children prop using the React.ReactNode
type.
{`import React, { ReactNode } from 'react';
type MyComponentProps = {
children: ReactNode;
};
const MyComponent: React.FC = ({ children }) => {
return (
{children}
);
};
export default MyComponent;`}
In the code snippet above, we define a functional component called MyComponent
that takes a prop called children
of type ReactNode
. We then render the children within a div
element.
Using ReactNodeArray
If you need to pass multiple children to your stateless functional component, you can use the React.ReactNodeArray
type.
{`import React, { ReactNodeArray } from 'react';
type MyComponentProps = {
children: ReactNodeArray;
};
const MyComponent: React.FC = ({ children }) => {
return (
{children}
);
};
export default MyComponent;`}
In the code snippet above, we define a functional component called MyComponent
that takes a prop called children
of type ReactNodeArray
. This allows us to pass an array of children to the component.
Usage example
Now let’s see how we can use our MyComponent
with children in TypeScript.
{`import React from 'react';
import MyComponent from './MyComponent';
const App: React.FC = () => {
return (
Hello, world!
This is a child component.
);
};
export default App;`}
In the code snippet above, we import our MyComponent
and use it as a parent component. We pass a h1
element and a p
element as children to our MyComponent
.
Conclusion
Using children with React Stateless Functional Components in TypeScript is straightforward. By defining the type of the children prop as ReactNode
or ReactNodeArray
, you can pass components or elements as children to your stateless functional components.
Leave a Reply