Specifying a type for a function prop
A prop can be a function. In this lesson, we'll learn how to strongly-type function props.
We'll cover the following
Strongly-typing a render prop #
An example of a function prop is a prop that allows the consumer of a component to control the rendering of part of a component. This is called a render prop.
Open the CodeSandbox project we were working on in the last lesson. Let’s add a render prop to our Hello
component to optionally allow the consumer to control how the message is rendered. The prop will be called renderMessage,
and the Hello
component will be as follows:
const Hello = ({
who,
renderMessage,
message = "How are you?"
}: Props) => (
<React.Fragment>
<p>
Hello, {who.name}
{who.friend && " my friend"}
</p>
{message && (renderMessage ? renderMessage(message) : <p>{message}</p>)}
</React.Fragment>
);
An example consumption of Hello
is as follows:
<Hello
who={{ name: "Bob", friend: true }}
message="Hey, how are you?"
renderMessage={m => <i>{m}</i>}
/>
So, what should the definition of the Props
type be now with the new renderMessage
prop?
Get hands-on with 1400+ tech skills courses.