Search code examples
javascriptreactjsnulldefault-value

Best practice to handle null props in React?


Consider I got two components:

// Hello.js

import React from "react";

export default function Hello(props) {
  const { name = "mike" } = props;
  return <div>Hello {name}</div>;
}
// App.js

import React from "react";
import Hello from "./Hello";

export default function App() {
  return (
    <div>
      <Hello name={null} />
    </div>
  );
}

// renders Hello

If I pass null props to the Hello component, The Hello component will not use the default value, instead, it will just use null as a value and render it.

The default value will only be used when i explicitly pass undefined or not pass anything:

<Hello name={undefined} />
<Hello />

// renders Hello mike

So my question is How should i handle null props correctly? Should i handle it in parent component when pass it to child component like this:

// App.js
<Hello name={getName() || 'mike'} />

Or i should handle it in child component like this:

// Hello.js

return <div>Hello {name || "mike"}</div>;

Is there any "best practice" to help handle this?


Solution

  • bad, cos somebody else will forget and yell WTF

    // App.js
    <Hello name={getName() || 'mike'} />
    

    so so, but this is ugly, assign default value is more elegant

    // Hello.js
    return <div>Hello {name || "mike"}</div>;
    

    better, why not just return string or undefined

    function getName(){
      ...
      return something || undefined
    }
    

    best, people wont always do so, how to make sure? TypeScript will check it when compile

    interface Props {
        name: string;
    }
    interface State {
        xxx: xxx
    }
    class Hello extends React.Component<Props, State> {
    
    

    choose as you like, cos best costs most