d||ell

#TIL: React's JSX Default Value

February 14, 2020 · ☕️ 1 min read

Today I learned about React JSX’s default value.

Consider the Button component below:

import React from 'react';
import Loader from '../Loader';

function Button ({  loading }) {
 return <button>{ loading ? <Loader /> : 'Click me!'}<button/>
}

A huge aha moment moments ago! When you supply props without a value, it will default to true.

So in a nutshell, these two JSX expressions below are equivalent:

<Button loading={true} />

<Button loading />

And so, if you use make use of JavaScript coercion nature. These two JSX expressions are also equivalent.

<Button loading={false}/>

<Button />

Plus tip! If you have type-checking in your React project, this could help.

type TButtonProps = {
  loading?: Boolean
}
// So if you do this the type checking won't complain
<Button />

@dorelljames

Personal blog by @dorelljames
I love you and coding!

Let me know your thoughts... 😊

What's next?

Continue reading articles using the links below...

Copyright © 2023,d||ell. Built with Gatsby. Source on GitHub.