If you use React v17+ with TypeScript & functional components in React.StrictMode, then:
1) Parent to Child
1.1) Parent Component, e.g. App.tsx
import Dashboard from "./components/Dashboard/Dashboard";
export default function App() {
return <Dashboard title="My Dashboard"></Dashboard>;
}
1.2) Child Component, e.g. Dashboard
// src/components/Dashboard/Dashboard.tsx
import React from "react";
type DashboardProps = {
title: string;
};
const Dashboard: React.FC<DashboardProps> = (props) => (
<div>Dashboard Component {props.title}</div>
);
export default Dashboard;
This is the same as above (excerpt):
//..
export default function Dashboard(props: DashboardProps) {
return <div>Dashboard Component {props.title}</div>;
}
Lazy-Loading
If you want to use "Lazy-Loading", you have to change the Dashboard component slightly or maybe use a Dashboard.lazy.tsx like:
import React, { lazy, Suspense } from 'react';
import { DashboardProps } from '../../Types';
const LazyDashboard = lazy(() => import('./Dashboard'));
const Dashboard = (props: DashboardProps) => (
<Suspense fallback={null}>
<LazyDashboard {...props} />
</Suspense>
);
export default Dashboard;
I've moved the DashboardProps into a new file due to reusability.
// Types/index.tsx
export type DashboardProps = {
title: string;
};
2) Child to Parent (this time with React.useState hook)
2.1) Parent, e.g. App.tsx
import Dashboard from "./components/Dashboard/Dashboard";
export default function App() {
const [messageFromChild, getMessageFromChild] = React.useState(
"Dad is waiting"
);
const sendDataToParent = (message: string) => {
getMessageFromChild(message);
};
return (
<div>
<Dashboard
props={{ title: "My Dear Dashboard" }}
sendDataToParent={sendDataToParent}
></Dashboard>
<div>
<strong>From Child to Parent:</strong> {messageFromChild}
</div>
</div>
);
}
2.2) Child, e.g. Dashboard.tsx
import React from "react";
import { DashboardProps } from "../../Types";
const Dashboard: React.FC<DashboardProps> = ({ props, sendDataToParent }) => (
<div>
<strong>From Parent to Child:</strong> {props.title}
<button
onClick={() => {
sendDataToParent("Hi Dad");
}}
>
Send to Parent
</button>
</div>
);
export default Dashboard;
2.3) Types, e.g. Types/index.tsx
export type DashboardProps = {
props: {
title: string;
};
sendDataToParent: (message: string) => void;
};
