Working with Props in React and TypeScript
This guide will walk you through the basics of using props in a React component while leveraging the power of TypeScript's static typing. Props allow you to pass data from a parent component to a child component in React.
Declaring Components with Props
In TypeScript, defining a component's props involves creating a type that outlines the expected structure of the props. This helps catch type-related errors early.
// Example: Declaring props for a PersonList component
type PersonListProps = {
names: {
first: string;
last: string;
}[];
};
export const PersonList = (props: PersonListProps) => {
// Component implementation here
};
Number Props
When passing a numerical value as a prop, you can define its type using TypeScript's number
type.
type GreetProps = {
messageCount: number;
};
String Props
For string-based props, use the string
type in TypeScript.
tsxCopy codetype GreetProps = {
name: string;
};
Boolean Props
Boolean props can be defined using the boolean
type.
type GreetProps = {
isLoggedIn: boolean;
};
Using Props in Components
Props can be accessed within the component by referring to the props
object.
export const Greeting = (props: GreetProps) => {
return (
<h2>
{props.isLoggedIn ? `Welcome ${props.name}` : 'Login'}
</h2>
);
};
Array Props
To pass an array of objects as a prop, specify the array structure in the prop's type definition.
type PersonListProps = {
names: {
first: string;
last: string;
}[];
};
Children Props
React components can also accept children's components as props. This allows you to pass JSX elements and structures directly into a component.
<Oscar>
<Heading>Oscar goes to Leonardo DiCaprio</Heading>
</Oscar>
To define a component that accepts children, you can use the React.ReactNode
type.
type OscarProps = {
children: React.ReactNode;
};
Here's an example of how you can create a Heading
component that accepts a string as its children prop:
type HeadingProps = {
children: string;
};
export const Heading = (props: HeadingProps) => {
return <h1>{props.children}</h1>;
};
Complete code
The complete code is found in the repository below, feel free to check.
Conclusion
Using TypeScript with React props enhances your development experience by catching type errors before runtime. This guide covered various types of props, using props in components, and even handling children's props. By adhering to these patterns, you'll write more reliable and maintainable React applications.
Feel free to explore more complex scenarios and advanced TypeScript features as you become more comfortable with the concepts outlined in this guide. Happy coding! ๐