Search code examples
javascriptcssreactjstypescriptstyled-components

How do I pass a variable/literal for a value in styled components?


I always use props as it's the basic way for managing different use cases, but I'm trying to change border color during the focus state of a styled input (is it possible to assign props to a focus state?).

I'm familiar with using props but even within the styled component, I'm not able to assign to a variable. i can't say {props => props.focused ? accentCol : null}. The only way I've been able to assign variables has been through inline styles. However, afaik there's no way to access focus state through inline styles :/

const accentCol = `{some redux function which retrieves different colors in different scenarios`

const styledInput = styled.input`
  background: #181a1a;
  border: 1px solid rgba(255, 255, 255, 0.4);
  &::placeholder {
  }
  &:focus {
    outline: none !important;
    border: solid 2px accentCol !important;
  }
`

how do I assign border color to a variable?


Solution

  • interface IProps {
      focus: string,
    }
    
    const variantsfocus = {
      primary: 'solid 2px accentCol',
    };
    
    const StyledInput = styled.input<IProps>`
      background: #181a1a;
      border: 1px solid rgba(255, 255, 255, 0.4);
      &::placeholder {
      }
      &:focus {
        outline: none !important;
        border: ${props => variantsfocus[props.focus]};
      }
    `
    

    I hope this would be helpful, you have to pass the prop in the component like

    <StyledInput focus="primary" />
    

    This link may be helpful also.