Categories
React Answers

How to Render Children Components with React Stateless Functional Component in TypeScript

Spread the love

Sometimes, we want to render child components in a stateless React function component with TypeScript.

In this article, we’ll look at how to render child components in a stateless React function component with TypeScript.

Use Children with React Stateless Functional Component in TypeScript

We can pass in the interface or type alias into the generic type argument of React.FunctionComponent to set the type for ur props.

As long as the alias or interface has the children prop, we can use the children prop.

For instance, we can write:

const Foo: React.FunctionComponent<FooProps> = props => (
  <div>
    <p>{props.bar}</p>
    <p>{props.children}</p>
  </div>
);

FooProps has the bar and children entries, so we can reference both in our component.

React.FC is the shorthand for React.FunctionComponent .

Before React 16.8, we use the React.StatelessComponent type instead.

For instance, we can write:

const Foo: React.StatelessComponent<{}> = props => (
  <div>{props.children}</div>
);

or:

const Foo : React.StatelessComponent<FooProps> = props => (
  <div>
    <p>{props.propInMyProps}</p>
    <p>{props.children}</p>
  </div>
);

React.SFC is the shorthand for React.StatelessComponent.

Conclusion

We can pass in the interface or type alias into the generic type argument of React.FunctionComponent to set the type for ur props.

As long as the alias or interface has the children prop, we can use the children prop.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *