React "as" Prop

 by Robin Wieruch
 - Edit this Post

You may have noticed the "as" prop when working with . Essentially the "as" prop allows you to replace rendered HTML elements in a React component from the outside by :

const Headline = ({ as = 'h1', children }) => {
const As = as;
return <As>{children}</As>;
};
const App = () => {
return (
<>
<Headline>Hello React</Headline>
<Headline as="h2">Hello React</Headline>
</>
);
};

Usually it is called "as" prop, however, one can see it also as "component", "element", "variant" prop -- or a combination of two of them. For example, one use case for using a combination of "component" and "variant" prop could be the following:

const Headline = ({ component, variant, children }) => {
const Component = component;
return <Component className={variant}>{children}</Component>;
};
const App = () => {
return (
<main>
<div>
<Headline component="h1" variant="h1">
Web Development Explained
</Headline>
</div>
<div>
<Headline component="h2" variant="h1">
React Explained
</Headline>
</div>
</main>
);
};

In this example, we have two headlines for two sections of an article. While both headlines should look the same in the article (variant), they should be semantically different (component), because there can only be one h1 HTML element on the page.

If you want to use TypeScript for the variant, component, or as prop, check out the following code snippet:

interface HeadlineProps {
component: React.ElementType;
variant: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
children: React.ReactNode;
}
const Headline: React.FC<HeadlineProps> = ({
component,
variant,
children,
}) => {
const Component = component;
return <Component className={variant}>{children}</Component>;
};

That's it. Especially when you are creating in-house UI component libraries or design systems, these props become important when dealing with combinations of semantics and aesthetics.

Keep reading about 

Eventually everyone came across the case that JavaScript's replace function, which is available on a JavaScript string primitive , does only replace one occurrence of the matched term. Here I want to…

A React Router tutorial which teaches you how to use Descendant Routes with React Router 6 . The code for this React Router v6 tutorial can be found over here . The previous tutorial of Nested…

The Road to React

Learn React by building real world applications. No setup configuration. No tooling. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get it on Amazon.