skip to Main Content

I’ve created a component that has default values of its props to be objects. Am I able to pass in a value for only 1 of the keys while leaving the others as default?

Example:

Let’s say this is the component:

export default function PageHeader({
  heading = {
    options: "",
    customStyles: {},
    text: ""
  }
}) {
  return (
      <h1 className={heading.options} style={heading.customStyles}>
        {heading.text}
      </h1>
  );
}

Assuming the only thing I want to change from the default prop object’s values is the text. Is there a way for me to do something like this:

<PageHeader heading = {...heading, text: 'New Text'} />

or

<PageHeader heading.text='New Text' />

Or would I have to pass in the entire heading prop object/not use an object and have each key be its own standalone prop?

2

Answers


  1. If you are set on passing the object you can do it a few ways.

    Consider this

    const defaultHeading = {
      options: {},
      customStyles: {},
      text: ""
    }
    
    export function Heading(props) {
      const heading = {...defaultHeading, ...props.heading} // combine so null values are overridden
    
    return (
          <h1 className={heading.options} style={heading.customStyles}>
            {heading.text}
          </h1>
      );
    }
    

    Or you can use null-coalescing

    export function Heading({ heading }) {
      
    return (
          <h1 className={heading.options ?? {}} style={heading.customStyles ?? {}}>
            {heading.text ?? ""}
          </h1>
      );
    }
    

    and call like so, only specifying the properties you want to change from default

    <PageHeader heading={{ text: "some other text" }} />

    Login or Signup to reply.
  2. I’d recommend using flattened properties instead of a header object with properties. You can leverage defaultProps to achieve the result you want without manually merging props:

    import type { CSSProperties, ReactNode } from "react";
    
    export default function PageHeader({
      className,
      style,
      children
    }: {
      className?: string;
      style?: CSSProperties;
      children?: ReactNode;
    }) {
      return (
        <h1 className={className} style={style}>
          {children}
        </h1>
      );
    }
    
    PageHeader.defaultProps = {
      className: "default-class",
      style: { textTransform: "uppercase" },
      children: "Default"
    };
    

    Here’s a demo utilizing the above code:

    Edit React leveraging defaultProps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search