This article covers the fundamentals of props and types of props in React and TypeScript. Without any further ado (like talking about the history of React or the benefits of using TypeScript), let’s get started.
Overview
Declaring Type of Props
You can use type or interface when defining types. Here’s a quick example:
export enum Role {
member = "member",
staff = "staff",
admin = "admin"
}
export interface UserProps {
id: string;
email: string;
age?: number;
isMarried?: boolean;
role: Role;
skills?: string[];
updateEmail?: (
id: string,
newEmail: string
) => {
success: boolean;
message: string;
};
}
const User = ({ id, email, role, skills }: UserProps) => {
return (
<>
<p>Id: {id}</p>
<p>Email: {email}</p>
<p>Role: {role}</p>
{skills && (
<ul>
{skills.map((skill) => (
<li key={skill}>{skill}</li>
))}
</ul>
)}
</>
);
};
export default User;
props.children
props.children is a special property of React components used to display whatever you include between the opening and closing tags when invoking a component. In this case, the best type of props.children is React.ReactNode. The type of props.children can also be React.ReactChild, React.ReactChild[], JSX.Element[], JSX.Element, but these types have some flaws, for example, JSX.Element[] doesn’t accept strings.
A Complete Example
Preview
The sample app we are going to build has 3 functional components: App, Wrapper, and User:
- App: The root component. User data, including id, email, age, role, skills, and a function called doSomething will be passed from here.
- Wrapper: This component determines the layout and style.
- User: This component displays detailed information about a user.
Writing Code
1. Initialize a new React TypeScript project:
npx create-react-app kindacode_ts_react --template typescript
2. Create 2 new files named User.tsx and Wrapper.tsx in the src folder.
3. Add the following to Wrapper.tsx:
// Wrapper.tsx
import React from "react";
interface WrapperProps {
children: React.ReactNode;
}
const Wrapper = ({ children }: WrapperProps) => {
return (
<div
style={{
backgroundColor: 'indigo',
color: 'white',
display: "flex",
flexDirection: "column",
padding: '50px',
fontSize: 24
}}
>
{children}
</div>
);
};
export default Wrapper;
4. Add the following to User.tsx:
// User.tsx
import React from "react";
import Wrapper from "./Wrapper";
export enum Role {
member = "member",
staff = "staff",
admin = "admin"
}
interface UserProps {
id: string;
email: string;
age?: number;
isMarried?: boolean;
role: Role;
skills?: string[];
doSomething: React.MouseEventHandler;
}
const User = ({
id,
email,
age,
isMarried,
role,
skills,
doSomething,
}: UserProps) => {
return (
<Wrapper>
<p>Id: {id}</p>
<p>Email: {email}</p>
{age && <p>Age: {age}</p>}
{isMarried && <p>Is Married: {isMarried}</p>}
<p>Role: {role}</p>
{skills && (
<ul>
{skills.map((skill) => (
<li key={skill}>{skill}</li>
))}
</ul>
)}
<button onClick={doSomething} style={{padding: '15px 40px'}}>Do something</button>
</Wrapper>
);
};
export default User;
5. Replace all of the default code in App.tsx with this:
// App.tsx
import React from "react";
import User, { Role } from "./User";
const user = {
id: "u1",
email: "[email protected]",
age: 34,
isMarried: false,
role: Role.member,
skills: ["React", "Node.js", "MySQL"],
doSomething: () => {
console.log(`Hello ${user.email}`);
},
};
const App = () => {
return (
<div>
<User
id={user.id}
email={user.email}
age={user.age}
isMarried={user.isMarried}
role={user.role}
skills={user.skills}
doSomething={user.doSomething}
/>
</div>
);
};
export default App;
6. Run your project and navigate to http://localhost:3000 to check the result.
Conclusion
We’ve gone through a complete example that focuses on props and types of props. If you’d like to explore more about modern React and TypeScript, take a look at the following articles:
- React + TypeScript: Re-render a Component on Window Resize
- React + TypeScript: Handling onScroll event
- React: Get the Width & Height of a dynamic Element
- React + TypeScript: Handle onCopy, onCut, and onPaste events
- React + TypeScript: onMouseOver & onMouseOut events
- React: Get the Position (X & Y) of an Element
You can also check our React category page and React Native category page for the latest tutorials and examples.