1

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Some people consider props spreading as an anti-pattern: vhudyma-blog.eu/react-antipatterns-props-spreading
All claims in this blog arent so accurate when you use types which is basically every modern project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.