How to declare default props in react functional component

Viewed 32264

I want to declare default props in a functional component

normally we would do this

function Body() {
    static defaultProps = {
        counter: 0
    }
    return (
        <div>
            body
        </div>
    );
}

this obviously doesn't work

6 Answers

This is usually called a functional component, not a hook component.

For the defaultProps you can do it like this:

const Body = ({ counter }) => {
    return (
        <div>
            {counter}
        </div>
    );
}

Body.defaultProps = {
    counter: 0
}
function Body({counter=0}) {
    return (
        <div>
            body
        </div>
    );
}

counter now has initial value of 0

You can do that simply like this

const Body = (props) => {
    const {foo = 'defaultValue'} = props;

    return <div>{foo}</div> // It will show defaultValue if props foo is undefined
}

Hooks are just regular functions, you can define default values the same way as you define them in regular functions

function useNameHook(initialName = "Asaf") {
  const [name, setName] = useState(initialName);

  // you can return here whatever you want, just the name,
  // just the setter or both
  return name;
}

function Comp({ name }) {
  const myName = useNameHook(name);

  return <h1>Hello {myName}</h1>;
}

function App() {
  return (
    <div className="App">
      {/* without name prop */}
      <Comp />
      {/* with name prop */}
      <Comp name="angry kiwi" />
    </div>
  );
}

You can declare defaultProps outside the functional component. In your case it would be something like this -

   function Body(props) {
    return (
        <div>
            {props.counter}
        </div>
    );
  }
  Body.defaultProps = {
      counter: 0
  }

This is for hooks but is not intended for functional components.

const defaultProps = {
  position: "end"
};

const Dropdown = (props) => {
   // The order of arguments is important.
  props = Object.assign({}, defaultProps, props);
  ...
}
Related