Is there a way, with styled components, to conditionally change the type of component?

Viewed 907

I have components that look identical with the same data, but sometimes I want it to be a link and sometimes a div, etc. Can I have it be one component (because they have identical styles) and do something like pass in a prop to change the type of component?

For example:

import styled, { css } from "styled-components";
import { Link } from "react-router-dom";

export const Container = styled.div`  *<<--- how do I make this styled.div OR styled(Link)*
    some styles here
`;
3 Answers

You can pass a prop in your component . Like prop === true -> show as div & if prop === false -> show as link. Then using ES6 you can achieve it as


import styled, { css } from "styled-components";
import { Link } from "react-router-dom";

export const Container = (prop) =  {

        { (prop===true) && return (JSX as a div) }

{(prop === false) && return (JSX for as a link) }

}

Use the forwardedAs prop


const MyComponent = () => (
  <Container forwardedAs={"a"}>
    ...
  </Container>
);

Use as prop, its part of the official API:

If you want to keep all the styling you've applied to a component but just switch out what's being ultimately rendered (be it a different HTML tag or a different custom component), you can use the "as" prop to do this at runtime.

const Div = styled.div`
  color: red;
`;

function App() {
  return (
    <Div className="App" as="span">
      Hello
    </Div>
  );
}

Generates:

<span class="sc-hKgILt eQjPkS App">Hello</span>

Edit As Prop

Related