relaxxpls
relaxxpls

Reputation: 33

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.

Upvotes: 0

Views: 604

Answers (2)

albseb
albseb

Reputation: 169

You could probably use the cloneElement method in React


return (
  <> 
    { React.cloneElement( icon, [props] }
  </>
)

It is similar to

<element.type {...element.props} {...props}>{children}</element.type>

To override some values you can do inline styling.

or otherwise you could use some css classes to override with selectors as well.

  • if you are going to use styled-icons
  • you can just simply provide it the props directly.
  • Styled Icons accept all the valid props of an <svg /> element

https://github.com/styled-icons/styled-icons#props

Upvotes: 0

Federkun
Federkun

Reputation: 36989

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>
  )
}

Upvotes: 1

Related Questions