Search code examples
htmlcssreactjsstyled-components

Can't target last of type in React Styled Component input


Hi using Styled components with React - building a split date input for day/month/year - the only change I want to make is that the width of the year input is double the length of the other two inputs, I've tried using :nth last-of-type etc but to no avail, I have a suspicion it is because how I'm rendering the inputs as components? Can anyone advise of a nice workaround?

Code:

const StyledInput = styled.input`

  display: block;

  height: 48px;
  width: 50px;
  margin-right: 12px;
  margin-top: 12px;
`;

  return (
    <StyledInputGroup>
      <label>
      <span>Day</span>
      <StyledInput
        type="text"
        maxLength="2"
        label="Day"
        value={day}
        onChange={(e) => setDay(e.target.value)}
      />
      </label>
      <label>
      <span>Month</span>
      <StyledInput
        type="text"
        maxLength="2"
        label="Month"
        value={month}
        onChange={(e) => setMonth(e.target.value)}
      />
      </label>
      <label>
      <span>Year</span>
      <StyledInput
        type="text"
        maxLength="4"
        value={year}
        onChange={(e) => setYear(e.target.value)}
      />
      </label>
    </StyledInputGroup>
  );

Simplified codepen: https://jsfiddle.net/4xzn8a5q/11/


Solution

  • last-child is not working like you are expecting. It is searching for labels and not inputs. If you want to use this selector, try to focus on label and then set the width of the input inside that label.

    So you need to first find the last label child and then apply the double width inside the input field of that label.

    Check this fiddle