How to Define React TypeScript Props
In this lesson, we'll introduce and type define Props to our recently created Listings function component.
Props & TypeScript#
📝 This lesson's quiz can be found - here.
🗒️ Solutions for this lesson's quiz can be found - here.
There are two main types of components in React - Class components and Functional components. Functional (or Function) components are functions that can accept props and return JSX. In our <Listings>
component we can see that the Listings component doesn't receive props yet, but returns JSX - which makes it a valid functional component.
import React from "react";
export const Listings = () => {
return <h2>TinyHouse Listings</h2>;
};
With that said, let's attempt to have the <Listings>
component now receive some props. We'll look to have the 'TinyHouse Listings'
text be given to the <Listings>
component from the parent. The parent, in this context, is the root src/index.tsx
file. In the src/index.tsx
file where <Listings>
is being rendered, we'll pass in a new prop labeled title
that has a string value of 'TinyHouse Listings'
.
render(
<Listings title="TinyHouse Listings" />,
document.getElementById("root")
);
TypeScript will throw an error since we haven't stated that the <Listings>
component is to accept a title
prop of type string
.
In the <Listings>
component, we'll specify that props
are being passed down and the title
field from props
is to be used in the <h2>
tag.
import React from "react";
export const Listings = props => {
return <h2>{props.title}</h2>;
};
This page is a preview of TinyHouse: A Fullstack React Masterclass with TypeScript and GraphQL