Search code examples
reactjsstyled-components

Dynamically style components passed as props


The goal is to style a prop inside a function (if the prop exists).

More specifically, I basically pass an icon (from styled-icons) as a prop to it and it is supposed to add styling to that icon.

This works with warnings:

const InputRounded = ({ type, placeholder, icon }) => {
  const Icon = styled(icon)`
    color: #807da0;
    width: 1.75rem;
    margin: 0 1.25rem 0 0.75rem;
  `

  return (
    <Container>
      <Input type={type} placeholder={placeholder} />
      <Icon />
    </Container>
  )
}

Here is how I call it:

import { LockPassword } from '@styled-icons/remix-line'

<Input type="password" placeholder="Password" icon={LockPassword} />

I am aware that one shouldn't create a component inside a function, but I have tried numerous ways otherwise and haven't reached anywhere. Any help for a better method would be greatly appreciated.


Solution

  • You can, very simply, pass a style prop to icon.

    const InputRounded = ({ type, placeholder, icon: Icon }) => {
      return (
        <Container>
          <Input type={type} placeholder={placeholder} />
          <Icon style={{ color: '#807da0', ... }} />
        </Container>
      )
    }