Home > Article > Web Front-end > Dynamic HTML Tag in React Components with the \'as\' prop
Imagine you're building a reusable This is a typical scenario when you want your HTML to be more semantic and SEO friendly. The solution is to let the consumer decide which HTML tag should be used to render the component. This is nothing new. Without the "as" prop, you'd need to create separate components for each use case, and it makes no sense. Don't do it! This is how you consume the "as" prop And this is the component definition React helps us with Typescript types. As an alternative to React.ElementType you can use or The above is the detailed content of Dynamic HTML Tag in React Components with the \'as\' prop. For more information, please follow other related articles on the PHP Chinese website!
The "as" prop
It's an industry standard "approach" that allows you to dynamically decide which HTML tag should be used to render the component. A lot of React Components library use it, like Chakra UI and Material UI.
import { Section } from './section';
const App = () => {
return (
<div>
<Section as="section">CTA</Section>
<Section as="article">My Article</Section>
<Section>This use the default HTML tag of the component</Section>
</div>
);
};
type SectionProps = {
as?: React.ElementType,
children: React.ReactNode,
}
export const Section = (props: SectionProps) => {
const { as: Tag = 'div', children } = props;
return <Tag>{children}</Tag>;
}
Typescript Support for the "as" prop
Using the typescript's React.ElementType type, provided by React, you will obtain autocomplete for your IDE, like this
type SectionProps = {
as?: keyof JSX.IntrinsicElements,
children: React.ReactNode,
}
type SectionProps = {
as?: keyof HTMLElementTagNameMap,
children: React.ReactNode,
}