How to work with styled components in my react app? How to work with styled components in my react app? reactjs reactjs

How to work with styled components in my react app?


styled.h1`...` (for example) returns a React component that works just like <h1>. In other words, you use <h1> like this:

<h1>h1's children</h1>

...so when you do const Heading = styled.h1`...`;, you'll use <Heading> the same way:

<Heading>Heading's children</Heading>

If you want a component that behaves differently, e.g. one that uses the title prop instead of children, you'll need to define such a component, and it will need to have a different name than the Heading component you already defined.

For example:

const styled = window.styled.default;const Heading = styled.h1`  background: red;`;const TitleHeading = ({title}) => <Heading>{title}</Heading>;// ...or...class StatefulTitleHeading extends React.Component {  render() {    return <Heading>{this.props.title}</Heading>;  }}ReactDOM.render(  <div>    <Heading>I'm Heading</Heading>    <TitleHeading title="I'm TitleHeading"/>    <StatefulTitleHeading title="I'm StatefulTitleHeading"/>  </div>,  document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><script src="https://unpkg.com/styled-components@1.4.3/dist/styled-components.js"></script><div id="container"></div>

Frankly, though, it makes more sense to just use the component returend by styled.h1 directly:

const Heading = styled.h1`...`;export default Heading;// ...then...<Heading>Children go here</Heading>

The semantics of children are already clear, and using <Heading title="Children go here"/> instead detracts significantly from that.


Let me make this really simple for you.

Let's create one styled component for heading named 'Heading'

const Heading = styled.h1`  color: 'black';  font-size: 2rem;`

and now you can use it like following.

<Heading>{this.props.title}</Heading>

How you manage to get the title prop as it's child is no concern of style component's. It only manages how that title looks. Styled component is not a container that maintains your app/business logic.

Now let's look at an example in it's entirety.

import styled from 'styled-components'// Heading.js (Your styled component)const Heading = styled.h1`  color: 'black';  font-size: 2rem;`export default Heading

and now your container that will use your styled component

// Header.jsx (Your container)class Header extends Component {  componentWillReceiveProps(nextProps) {    // This your title that you receive as props    console.log(nextProps.title)  }  render() {    const { title } = this.props    return (      <div id="wrapper">        <Heading>{title}</Heading>      </div>    )  }}

I hope that helps. Let me know if you need further clarification.


matomo