OctaviaLo
OctaviaLo

Reputation: 1396

Pass prop to nested element in styled component

I would like to pass a prop to a nested style for a paragraph element, but it looks like I can't put the prop directly on the element. How do I achieve this? I only want to apply the uppercase transformation to only one of the p elements...

const MailingListWrapper = styled.div`
  display: flex;
  & > p {
    text-transform: ${props => props.uppercase || 'none'};
  }
`

function JoinUs() {
  return (
    <MailingListWrapper>
      <p uppercase="uppercase">Join our mailing list!</p>
      <p>Never miss an update</p>
    </MailingListWrapper>
  )
}

Upvotes: 2

Views: 2324

Answers (2)

OctaviaLo
OctaviaLo

Reputation: 1396

Putting the final result here for posterity based on Tholle's answer...

const MailingListWrapper = styled.div`
  display: flex;
  & > p {
    color: gold;
    &.uppercase {
      text-transform: uppercase;
    }
  }
`

Upvotes: 1

Tholle
Tholle

Reputation: 112777

The props you have access to in the template string used when creating the MailingListWrapper component are the props given to MailingListWrapper when you use it.

You could instead give the p tag a uppercase className and just apply the styles to p tags with the uppercase class.

const MailingListWrapper = styled.div`
  display: flex;
  & > p.uppercase {
    text-transform: uppercase;
  }
`;

function JoinUs() {
  return (
    <MailingListWrapper>
      <p className="uppercase">Join our mailing list!</p>
      <p>Never miss an update</p>
    </MailingListWrapper>
  );
}

Upvotes: 0

Related Questions