How to default a state variable to a property value in a functional React component

Post author: Adam VanBuskirk
Adam VanBuskirk
6/18/23 in
Tech
ReactTypeScript

To default a state variable to a property value in a functional React component, you can use the useState hook in combination with the nullish coalescing operator (??) to set the initial state based on the value of a prop. Here’s an example:

import React, { useState } from 'react';

interface MyComponentProps {
  defaultValue: string;
}

const MyComponent: React.FC<MyComponentProps> = ({ defaultValue }) => {
  const [value, setValue] = useState<string>(defaultValue ?? '');

  // ...

  return (
    <div>
      <input
        type="text"
        value={value}
        onChange={(e) => setValue(e.target.value)}
      />
    </div>
  );
};

export default MyComponent;

In the above example, the MyComponent functional component receives a prop called defaultValue. We use the useState hook to initialize a state variable value, and we set its initial value to defaultValue ?? ''.

The nullish coalescing operator (??) checks if defaultValue is null or undefined. If it is, it falls back to an empty string ('') as the default value for the state variable.

By using this approach, the value state variable will default to the value of the defaultValue prop, but if the prop is not provided or is null/undefined, it will default to an empty string.

Sign up today for our weekly newsletter about AI, SEO, and Entrepreneurship

Leave a Reply

Your email address will not be published. Required fields are marked *


Read Next




© 2024 Menyu LLC