Contextual styling of styled ReactJS components

I'm having problems with Styled Components and I'm not sure if this is a technical limitation, or if my mental model of how to use them is wrong.

In this example (I just wrote it quickly in the Codepen, so ignore the spelling mistakes) I have a component that is the username in between. I want to be able to use this component anywhere, so its styling is pretty minimal:

// From User.js    
import React from 'react';
import styled from 'styled-components';

const Username = styled.span`
  color: black;
`

const User = () => (
  <UserName>bla</Username>
);

export default User;

      

I want to use this range in another component, but in this case, I want its style to be overridden in this context:

// From Userblock.js
import React from 'react';
import styled from 'styled-components';
import User from './user';

const UserWrapper = styled.div`
  // Some styles
`

const User = styled(User)`
  color: red; // Different color when displayed in a UserBlock
`

const UserBlock = () => (
  <UserWrapper>
    <User />
  </UserWrapper>
);

export default UserBlock;

      

From what I know, this is a way to set the styling for a third party component (and that works elsewhere in my application) and it should work as far as I can tell, but I get nothing.

Also, back to the question of the mental model - is this how you should be doing this when using styled components?

Thanks for any help!

+3


source to share


1 answer


When you terminate a normal React component with styled(X)

, you need to make sure to attach the class that styled-components

passes in
.

This means that for your example, this will solve the problem:



const User = (props) => (
  <UserName className={props.className}>bla</Username>
);

      

When overriding the styles of an existing component, it styled-components

goes ahead, generates a class, injects it, and passes it to the component. This means that if you don't attach the class to anything, you will never see the styles! (see documentation for more info)

+2


source







All Articles