Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: The best way to pass html attributes as props

For instance, I want to behave a Button as a normal button and enhance the component.

<Button type="submit" className="btn">Click me!</Button>

leads to an html element:

<button type="submit" className="btn">Click me!</button>

Is there a way to write the Button component like this?:

const Button = ({children, ...htmlAttributesOnly}) => (
    <button {...htmlAttributesOnly}>{children}</button>
)

The idea behind is to make a component as flexible as possible by giving access to all of its html elements' attributes. Or do I have to repeat every html element attribute?

like image 907
sebastianspiller Avatar asked Oct 23 '25 19:10

sebastianspiller


1 Answers

You were really close to an answer, just wrap your props in curly braces:

const Button = ({ children, ...rest }) => (
    <button {...rest}>{children}</button>
)
like image 81
Theroux Avatar answered Oct 26 '25 08:10

Theroux