Understanding React Props with TypeScript: A Practical Example
As I continue my journey with React and TypeScript, I’ve been diving deeper into how to effectively use props in my components. Today, I explored a practical example that I found quite enlightening. This example involves three components: Login
, Profile
, and Private
, where Private
conditionally renders either Login
or Profile
based on the user's login status. Let's walk through this step by step.
The Login
Component
First, we have a simple Login
component. This component doesn't take any props and simply renders a message asking the user to log in.
export const Login = () => {
return (
<div>
Please login to proceed
</div>
);
}
The Profile
Component
Next is the Profile
component, which takes a prop called name
. This prop is typed using a TypeScript type definition ProfilePropType
.
export type ProfilePropType = {
name: string;
};
export const Profile = ({ name }: ProfilePropType) => {
return (
<div>
Hello Private Profile Component, {name}
</div>
);
};
The Private
Component
The Private
component is where the magic happens. This component takes two props: isLoggedin
and Component
. The Component
prop is typed as React.ComponentType<ProfilePropType>
, meaning it should be a React component that expects ProfilePropType
as its props. Depending on the isLoggedin
status, it either renders the Login
component or the Profile
component, passing the name "Jahid" as a prop to Profile
.
import React from "react";
import { Login } from "./Login";
import { ProfilePropType } from "./Profile";
type privatePropType = {
isLoggedin: boolean,
Component: React.ComponentType<ProfilePropType>;
};
export const Private = ({ isLoggedin, Component }: privatePropType) => {
if (isLoggedin) {
return <Component name="Jahid" />;
} else {
return <Login />;
}
};
Bringing It All Together
To use these components, you would typically have a state that determines whether the user is logged in. Here is a simple example of how you might use the Private
component in your application:
import React, { useState } from "react";
import { Private } from "./Private";
import { Profile } from "./Profile";
const App = () => {
const [isLoggedin, setIsLoggedin] = useState(false);
return (
<div>
<button onClick={() => setIsLoggedin(!isLoggedin)}>
{isLoggedin ? "Logout" : "Login"}
</button>
<Private isLoggedin={isLoggedin} Component={Profile} />
</div>
);
};
export default App;
Clicking the button toggles the login state, which in turn changes what the Private
component renders.
I hope you found this walkthrough helpful! Feel free to share your thoughts and questions in the comments below & Don’t forget to follow . Happy coding .