ReactJS Prop Handling

Account Required

This free lesson is available if you sign in.
If you don't have an account, you can sign up for free.

ReactJS Prop Handling

Sign in to access this content

You must sign in to access this content.
If you don't have an account you can sign up for free!

React Props Basics

Custom elements can accept props as arguments.

App.tsx
export default function App() {
return (
<Example message="Hello Fam!" />
);
}

type ExampleProps = {
message: string,
};

const Example = (props: ExampleProps) => {
return (
<div>Message: {props.message}</div>
);
}

ReactNode type

The type React.ReactNode can be used to accept any variable that react supports for rendering to the DOM.

App.tsx
export default function App() {
return (
<Example message={<b>Hello Fam!</b>} />
);
}

type ExampleProps = {
message: React.ReactNode;
}

const Example = (props: ExampleProps) => {
return (
<div>Message: {props.message}</div>
);
}

Children Prop

The children prop has special meaning withing react and can be passed in between the opening and closing JSX tags.

App.tsx
export default function App() {
return (
<Example>
<span>Hi <b>Fam!</b></span>
</Example>
);
}

type ExampleProps = {
children?: React.ReactNode;
}

const Example = (props: ExampleProps) => {
return (
<div>
{props.children}
</div>
);
}

Self Closing Tags and children

You can provide children for self closing tags as well.

App.tsx
export default function App() {
return (
<Example children={<span>Hi <b>Fam!</b></span>} />
);
}

type ExampleProps = {
children?: React.ReactNode;
}

const Example = (props: ExampleProps) => {
return (
<div>
{props.children}
</div>
);
}

But it is not recommended to set the children prop explicitly, as its much more conventional to let children be passed in explicitly as the contents of an open/close JSX pair.

React.PropsWithChildren type

Instead of defining the children prop explicitly you can use the utility type React.PropsWithChildren.

App.tsx
export default function App() {
return (
<Example message='in a bottle'>
are cute
</Example>
);
}

type ExampleProps = React.PropsWithChildren<{
message: string,
}>;

const Example = (props: ExampleProps) => {
return (
<div>
message {props.message}
<br />
children {props.children}
</div>
);
}

Prop Destructing and Default Values

You can use JavaScript destructuring to clean up the component function parameters. This even allows you to add default values to props.

App.tsx
export default function App() {
return (
<Example
message='in a bottle'
/>
);
}

type ExampleProps = {
message: string,
required?: boolean,
};

const Example = ({
message,
required = true,
}: ExampleProps) => {
return (
<div>
message: {message}
<br />
required: {required ? 'true' : 'false'}
</div>
);
}

Shorthand Boolean Props

In JSX for boolean values for true you don't need to explicitly list them out like propName={true}. Instead if you just add propName it is implicitly passed set to true e.g. in the below example required means required={true}.

App.tsx
export default function App() {
return (
<Example
required
/>
);
}

type ExampleProps = {
required: boolean,
};

const Example = ({
required,
}: ExampleProps) => {
return (
<div>
required: {required ? 'true' : 'false'}
</div>
);
}

Spread Props

You can spread props from an object by using {...props}.

App.tsx
export default function App() {
const props: ExampleProps = {
song: 'message in a bottle',
by: 'police'
};
return (
<Example
{...props}
/>
);
}

type ExampleProps = {
song: string,
by: string,
};
const Example = ({ song, by }: ExampleProps) => {
return (
<div>
<i>{song}</i>
<br />
by <b>{by}</b>
</div>
);
}

Props are readonly

You cannot mutate the props object that gets passed into the react component. If you attempt a mutation the component will fail. This can be observed in the following example which will fail to render as we try to mutate the props object.

App.tsx
export default function App() {
return (
<Example message='Hello' />
);
}

type ExampleProps = {
message: string,
};

const Example = (props: ExampleProps) => {
// ❌ this will cause a runtime error
// 🤕 The component will not render
props.message = 'Attempt Mutation 🦁';
return (
<div>{props.message}</div>
);
};
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

In this lesson, we will look at all that you need to know in order to use props effectively in React, including what are props, the types, skeptic type definitions, what are React children, what are self causing tags, a special shorthand for Boolean, using objects as props, spreading props, why the type react node is so important, why all props should be treated as read and what happens if we don't follow this rule. And having this knowledge will really help you become a better React developer. So let's go. PROPS stands for properties and the fundamental objective of props within React is the ability to provide values to components so we can customize the behavior.

00:35

So to demonstrate the usage of props and its various features, we will be using a simple custom component as we saw in our previous lesson. Right now, this component is rendering a simple tiv with some simple text. As an example. We can customize the simple text that this component is showing by passing in a prop that contains a message property. We can pass in a custom message, for example, hello fam. And now instead of rendering the text simple component, we will render out props message. And now when the application refreshes, you can see that the message is passed in and rendered correctly.

01:08

An additional thing worth mentioning here is that it is conventional to name the type for the props as component followed by props. Here the component is called example and therefore we call the type example props. In addition to simple primitive types like string, a very important type to be aware of when working with react props is the type called react node. So let's take a look at why this type is so important. React node is a type that is provided by the react type definitions and we can point a message object to be of type react node. Now react node actually accepts anything that can be rendered by react.

01:42

As we have seen. A string is something that React can render perfectly fine and therefore string is a perfectly valid message of type react node. But with react node, in addition to strings, we can actually render any other JS six element as well. For example, a bold text containing Hello F, and you can see that this passes through to the example component and prop start message is now the bold text that we pass in. Now reactor is not a complete free for all. It actually does do some type checking to make sure that the things that you pass in are something that react can render. For example, if you have an arbitrary object,

02:15

an object is not something that react can render by default. So if you try to pass it in for the message which is of type react node, we get a nice compiled time error because it will crash at run time. Now that we understand the type react node a bit better, there is a special prop that we can look at within react that is conventionally of type react node called children. Now we can define a member called children within our props explicitly we are marking it as optional and it'll be of type react dot react node. As this prop is of type react node, we can render it in any interation that we want.

02:49

For example, we can render it inside a simple div. This prop has special meaning within react, and the way you pass it is by placing it within a pair of opening and closing tags. For example, here we are providing the children prop by placing it between an opening example and a closing example tag. And actually this is exactly how it is happening within the built-in div component as well. This brings us to another important concept within React, which is is there any difference between a pair of opening and closing tags versus a single self-closing tag? And the answer to this question is

03:21

that using a paid tag is just a neat shorthand for providing children. If your component does not use children, you do not need to use a paid tag and self-closing tags are the way to go. And in fact, even in a self-closing tag, we can explicitly provide the children prop and you can see this behaves exactly as a pair of opening and closing tags that we saw before. But of course, if you are using children, it is much more conventional to use a pair of opening and closing tags because that is closer to what you would write in conventional HTMO children is actually such a core part of react

03:54

of development that there is actually a special type within TypeScript to help make it easy to define props with children. For example, hey, we have a component that takes a children prop as well as a message prop. We can actually get rid of the children prop and pass the remaining type into a generic type provided by the react TypeScript type definitions, which is react props with children and this will automatically add children to whatever type we pass in. So the final result of example props will be the same as what we saw before, which is it'll have a message of type string and an optional children prop

04:27

of type react react node, and we can verify that when we hover over props to children within the render function for the prop parameter within components, it's actually quite conventional to combine it with other features of JavaScript which are destructuring and default values. For example, in this simple component we can destructure props into its constituents, which in this case is just a simple message object and this allows us to use message directly and not have to do props dot message every time we want to use this particular prop. Now this becomes even more powerful when you combine it

04:59

with optional properties. For example, we can add another member to the props called required, which is going to be of type bullion. However, this particular property is going to be optional. Now if you want the default value for the required prop to be true, we can do that quite easily once we have destructuring because we can add the optional default right after we destructure required from the past in props. And now even though we are not passing in the required property in our simple usage, you can see that when we render it out, it is defaulting to the value of true for bullion password.

05:33

Within React, there is actually even a nice shorthand that we can use when we want to provide a value of true as an example, we can explicitly provide a value of false, and as you can see, it renders to the string false. Or alternatively, we can explicitly provide a value of true and as you would expect, it renders the string true. Now, a neat feature within JSX is that when you want to provide a value of true, you don't actually need to list It out as an explicit assignment to the literal true. And in fact, if you remove it, it would behave exactly the same as if we were assigning the value true to the required prop.

06:07

Another trick that is often used with react props is the ability to spread props instead of having to list them out individually. For example, hey, we have a simple object contains a member's song and by and by coincidence, these are exactly the props that are expected by the example component. Now, instead of having to assign the props one by one, we can actually spread the props into the example component. And this would be exactly the same as us saying that song should be song and by should be by additionally. After we have done the spread, we can override any of the values.

06:39

For example, we can change the value for the song prop and leave the by coming in from that spread. A strict rule that must always be followed is that props must be treated as a read only within your function bodies. For example, hey we have a simple example component where we are passing in a message string. We can provide any string over here, and when we use props message, that is exactly what gets trended out. However, what happens if we try to change the message property off of props, for example, say props message is equal to some different string. As you can see, it actually renders nothing

07:13

because the application has actually crashed. If you open up the browser console, we can see the reason that the props object is actually immutable and we should not try to change this. Remember for example, assigning message to a different string as that will result in a runtime error. Now, this particular thing is a non-issue when you are using destructuring because you are essentially creating local variables just within the function and you own these variables. So you can of course assign them to different values. For example, hey, we are assigning message to a different string and this will work perfectly fine. Hopefully now you have a firmer grip on

07:46

what are props within react. Thank you for joining me and I'll see you in the next one.