-1

I am writing a React application with styled components, creating a library of reusable components for my application, but I encounter the problem of inheritance between sister components when trying to give a property to a label that is next to my input when the input is required, but it does not work. I have tried with:

// Form.js
import { StyledLabel, StyledInput } from './styles.js'
<StyledLabel>Mi Label 1</StyledLabel>
<StyledInput required/>

// ./styles.js
import styled from 'styled-components'

export const StyledInput = styled.input`
  border: 1px #dddd solid;
`

export const StyledLabel = styled.label`
  font-size: 10px;
  ${StyledInput}['required'] + & {
    &::after {
      content: '*'
    }
  }
`

The result only returns the form without the *

Does anyone know how I can detect from Styled Components when an input has the required HTML attribute, and show the *

David Acevedo
  • 173
  • 1
  • 6

1 Answers1

0

Pseudo-selectors in styled-components work just like they do in CSS. (or rather, Sass).
So you can do what you want this way:

const Wrapper = styled.div`
label {
    &:after {
    content: "${p => p.required && "*"}";
    color: red;
  }
}`;
const Form = () => {
return (
    <Wrapper required>
    <label>Mi Label 1</label>
    <input />
    </Wrapper>
);
};

But if you want don't want to pass props of the input element to its parent you can do it this way:

const Wrapper = styled.div`
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
`;
const Example = styled.input`
+ label {
      &:after {
        content: "${p => p.required && "*"}";
        color: red;
      }
    }
`;
const Form = () => {
  return (
    <Wrapper required>
      <Example />
      <label>My Label 1</label>
    </Wrapper>
  );
};

more info in resources:
Before and After pseudo classes used with styled-components

https://github.com/styled-components/styled-components/issues/388

https://github.com/styled-components/styled-components/issues/74

Shahab Emami
  • 324
  • 1
  • 7