We could pass all HTML attributes to a React component as a prop and then inside the component’s render function assign those props to the actual DOM HTML element.
const Foo = ({style}) => (
<div style={style}> // assigning inline style to HTML dom element
This is Foo
</div>
)
<Foo style={color: 'red'} /> // passing style as a prop to Foo react component
You can use JSX spread attributes
and make it more flexible so you won’t have to specify individual HTML attributes as a prop. You simply spread restProps over your HTML element.
const Foo({ name, ...restProps }) => {
return <div {...restProps}>{name}</div>;
}
Now you can pass DOM attributes to Foo and they’ll be passed through to div
.
<Foo
name="This is Foo"
className="foo-class"
id="my-foo"
style="color: red"
/>
When you use <> ... </>
this is a shorthand of <React.Fragment>...</React.Fragment>
which lets you only group multiple list of children WITHOUT adding extra node to the DOM when it gets rendered.
return (
<>
<Foo />
<Foo />
<Foo />
</>
);
This will render as
<div>This is Foo</div>
<div>This is Foo</div>
<div>This is Foo</div>
so if you find yourself need to pass a HTML attribute to <>...</>
you can simply change react fragment to a <div>...</div>
or <span>...</span>
or other proper HTML elements and set your attribute on.