Photo by Lautaro Andreani on Unsplash

This is an ongoing effort to give a general overview of the guiding ideas and React’s foundational concepts with typescript.

Here is the link to the previous article.

Master the React Fundamentals: Basics 02 | by Mahesh Guntumadugu | Oct, 2023 | Medium

Let’s get started:

In this article, we will learn how to pass children to different components.

Scenario: We want to pass props from one component to another component and specifically accept different types. I will be using TypeScript types to show how cleanly we can reuse props using react and Typescript.

AlertBasic.tsx

interface Props {
children: string;
}
const AlertBasic = ({ children }: Props) => {
return <div className="alert alert-primary">{children}</div>;
};

export default AlertBasic;

App.tsx

import AlertBasic from "./components/AlertBasic";
function App() {
const text = "simple text message";
return (
<div>
<AlertBasic children={text}></AlertBasic>
</div>
);
}

export default App;

Output:

Now let’s see how we can leverage Typescript types. The idea is that by defining the children prop as a separate and reusable component.

AlertAdvanced.tsx

import { ReactNode } from "react";
interface Props {
children: ReactNode | ReactNode[] | JSX.Element | JSX.Element[];
}
const AlertAdvanced = ({ children }: Props) => {
return <div className="alert alert-primary">{children}</div>;
};

export default AlertAdvanced;

Note: The css classes you see in these code snippets are part of bootstrap library.

If you observe closely, we are defining different types to our children and based on our need in different components, we can simply write markup as needed.

App.tsx

import React from "react";
function App() {
const jsxMarkUp = (
<div>
<b> bold: Hello world jsx</b>
<br />
<i> italic: Hello world jsx</i>
<br />
<span> normal Hello world jsx</span>
</div>
);

let reactNode = React.createElement(
"h1",
{ style: { color: "red" } },
"Master React typescript features one step at a time"
);
return (
<div>
<AlertAdvanced children={jsxMarkUp}></AlertAdvanced>
<AlertAdvanced children={reactNode}></AlertAdvanced>
</div>
);
}

export default App;

Output:

See the magic. You can use this technique in multiple components without duplicating the code. This helps keep your codebase clean and organized!

In conclusion, this is just one example of how to reuse props in React and TypeScript. We can apply this simple technique to any component to solve different use cases (ex: navigation, modals, etc.)

Now that you’re familiar with this technique, let your curiosity drive you to explore how you can experiment with it, one step at a time.

If you have come this far and hope you like this article, you can encourage me with your clap and by sharing this article within your network. That’s all for now.

--

--

Mahesh Guntumadugu

I'm not just a Senior Engineer— My belief? The world is a better place when we lift each other up. 😃. https://www.curiousengineers.in