Search code examples
javascriptcssreactjsstyled-components

Styled Components in React app with dynamic text


I am working on a React app and using styled-components. So far things have gone well and I really like it but I am having some issues with making my styled-components as reuseable as I want them to be.

I feel like part of my problem is that I am still learning some about React and styled-components.

The app is built with react-boilerplate so my component markup is based off of their example on how to use styled-components. I am also using Material UI.

import React from 'react';
import styled from 'styled-components';
import ListSubheader from 'material-ui/List/ListSubheader';

// styles for list subheader
const StyledListSubheade = styled(ListSubheader)`
  && {
    color: #fff;
    font-size: 0.75em;
    line-height: 16px;
    letter-spacing: 1px;
    text-transform: uppercase;
    padding: 12px 16px 20px;
  }
`;

class ListSubheader extends React.Component {
  render() {
    return (
      <StyledListSubheader>Title</StyledListSubheader>
    );
  }
}

export default ListSubheader;

Pretty easy right? But what do I do when I want to change the text within StyledListSubheader in each component? What if I want to import ListSubheader in two different components and I want the text to be Title in one and Example in the other component? How do I dynamically change that text?

Any help is appreciated! Thank you!


Solution

  • This is most easily done with the children prop of ListSubHeader:

    class ListSubheader extends React.Component {
      render() {
        return (
          <StyledListSubheader>{this.props.children}</StyledListSubheader>
        );
      }
    }
    

    Which you can now user in other components as:

    <ListSubheader>Whatever you like</ListSubheader>