Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare default props in react functional component

Tags:

reactjs

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

like image 634
angry kiwi Avatar asked Jun 19 '19 06:06

angry kiwi


People also ask

How do you declare a default prop?

You can define default props this way: export class Counter extends React. Component { constructor(props) { super(props); this. state = {count: props.

Is it possible to define default props inside child component?

While most React components receive their props from a parent component, it's also possible to specify default props. To do so, you simply assign a defaultProps object to the component; when React renders the component, the default props will be used unless the parent overrides them.

How do you pass default value in React?

To set a default value for an input element in React: Pass the default value as a parameter to the useState hook for controlled fields. Set the defaultValue prop on uncontrolled input fields.

Is defaultProps deprecated?

Because defaultProps on functions will eventually get deprecated.


4 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
}
like image 136
Arnaud Christ Avatar answered Oct 07 '22 18:10

Arnaud Christ


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

counter now has initial value of 0

like image 29
angry kiwi Avatar answered Oct 07 '22 18:10

angry kiwi


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>
  );
}
like image 20
Asaf Aviv Avatar answered Oct 07 '22 19:10

Asaf Aviv


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
}
like image 38
bkm412 Avatar answered Oct 07 '22 20:10

bkm412