theairbend3r
theairbend3r

Reputation: 799

Add props as an HTML attribute in a React.js component

I recently started using Next.js and Tailwindcss. I want to create a custom component that can be used as follows -

<CustomComponent> Hello World </CustomComponent>

While searching for how to use this, I came across an answer which said -

const CustomComponent = props => {
  return (
    <>
      <div {...props} className="text-red-900" />
    </>
  )
}

In my example, the CustomComponent will simple make the text-color to a shade of red.

I can now use this component as <CustomComponent> Hello World </CustomComponent>.

What I don't understand is this line - <div {...props} className="text-red-900" />. I couldn't find anything like this in the reactjs docs.

Is this an appropriate way of passing props as HTML attributes? How does it work?

Upvotes: 1

Views: 1589

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

Here are equivalent components:

const CustomComponent = (props) => {
  return <div className="text-red-900" {...props} />;
};

// props={prop1,prop2,className}
const CustomComponent = ({ ...props }) => {
  return <div className="text-red-900" {...props} />;
};

const CustomComponent = ({ prop1, prop2, className }) => {
  // className will be overridden if its valid
  return <div className="text-red-900" prop1={prop1} prop2={prop2} className={className} />;
};

Note that better to use spread syntax (for object literals) after the inline style (className) which makes it more generic.

As for why spreading the property is a valid syntax?

You have a Spread Attributes explained in the docs, remember that JSX is converted to React.createElement which accepts the props as an argument.

Upvotes: 4

Related Questions