Search code examples
htmlcssreactjscss-selectorsstyled-components

How to add CSS to "not the first" rendered Styled Component


I've got a component with some pretty unique styling. The component basically renders horizontal rows (with 2 inputs, and an icon: StyledButton with a Message (remove)).

The component allows users to add/ remove as many rows as they wish, but I want to directly target any instance of the StyledButton that isn't the first one. I've tried the commonly suggested answers but the issue may be the fact that the entire component is being rendered each time and the CSS can't reach that far.

Any suggestions would be great.

const StyledButton = styled(Button)`
  margin-top: 14px;
`;

  return (
    <div className={className}>
      {objects.map((enteredObject, index) => (
        <RepeatableAttributeSetContextProvider
          form={form}
          object={enteredObject}
          key={`${enteredObject.key}-${enteredObject.repeatIndex}`}
        >
          <StyledHorizontalAttributes className="attributeset-row">
            {enteredObject.attributeCollection.questions
              .filter(filterRepeatAttributes)
              .map((attribute) => (
                <Fragment key={attribute.key}>
                  {renderAttribute(enteredObject, attribute, formLayout)}
                </Fragment>
              ))}
            <StyledButton
              type="link"
              buttonStyle="LINK"
              name="delete"
              dataId={`delete-${enteredObject.key}-${index}`}
              isOberonIcon
              isIconButton
              icon="bin"
              onClick={() => onRemove(enteredObject)}
            >
              <Message id="Form.Button.Remove" defaultMessage="Remove" />
            </StyledButton>
          </StyledHorizontalAttributes>
        </RepeatableAttributeSetContextProvider>
      ))}
    </div>
  );

Solution

  • const StyledHorizontalAttributesTable = styled(StyledHorizontalAttributes)`
      & + & {
        .remove-btn {
          background-color: lightblue;
        }
      }
    `;
    

    worked using the above thanks to this answer: Specific targeting of CSS classes with Styled Components not being rendered - React