Sometimes, we want to add custom HTML attributes in our React JSX code.
In this article, we’ll look at how to add custom HTML attributes in our React JSX code.
How to Add Custom HTML Attributes in JSX
With React 16, we can add custom attributes natively.
For instance, we can write:
render() {
return (
<div data-foo="bar" />
);
}
We can just add it straight into our HTML elements without doing anything special.
Use Children with React Stateless Functional Component in TypeScript
We can pass in the interface or type alias into the generic type argument of React.FunctionComponent
to set the type for ur props.
As long as the alias or interface has the children
prop, we can use the children
prop.
For instance, we can write:
const Foo: React.FunctionComponent<FooProps> = props => (
<div>
<p>{props.bar}</p>
<p>{props.children}</p>
</div>
);
FooProps
has the bar
and children
entries, so we can reference both in our component.
React.FC
is the shorthand for React.FunctionComponent
.
Before React 16.8, we use the React.StatelessComponent
type instead.
For instance, we can write:
const Foo: React.StatelessComponent<{}> = props => (
<div>{props.children}</div>
);
or:
const Foo : React.StatelessComponent<FooProps> = props => (
<div>
<p>{props.propInMyProps}</p>
<p>{props.children}</p>
</div>
);
React.SFC
is the shorthand for React.StatelessComponent
.
Conclusion
With React 16, we can add custom attributes natively.