When creating a React component in TypeScript, it is important to correctly type the component and specify the type it returns, which should be a component itself. Failure to do so will result in an error. Let's take a look at an example:
import React from "react";
export const Child = () => {
return {
name:"Edem"
}
};
const Parent = () => {
return (
<>
<Child/>
</>
);
};
In the above code snippet, there are several errors. Firstly, the component Child is returning an object instead of a valid JSX element. Additionally, the typings are missing, which can lead to potential issues.
To fix this, we can apply the type definition React.FC (representing a React Function Component) to the Child component. This enforces that the component returns a valid JSX element. Here is the corrected solution:
import React from "react";
export const Child:React.FC = () => {
return <div>Hi there</div>
};
const Parent = () => {
return (
<>
<Child />
</>
);
};
Now, let's consider a scenario where we want to pass some props to the child component. In such cases, we need to inform the child component about the expected prop types. This can be achieved by using interfaces/type. Here is an updated example:
import React from "react";
interface Props {
content: string;
}
export const Child:React.FC<Props> = (props) => {
return <div>{props.content}</div>
};
const Parent = () => {
return (
<>
<Child content={"Hi there"} />
</>
);
};
By following these practices, we can ensure proper typing and make our React components more robust, reliable and maintainable when using TypeScript.
Top comments (1)
Nice, I did something similar, but using plain js: Create a typing game in javascript to measure wpm speed .