Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass props of React component to styled component

I am trying set the height of a styled component based on the props of the React component it is in.

I tried the following:

const Styled = styled.div`
    height: ${props => props.height}
`

class Parent extends React.Component {
  render() {
      return (
          <Styled height={this.props.height}/>
      )
  }
}

But somehow it doesn't work. Can somebody help me out? What is the best practice for what I am trying to do?

like image 631
oezguensi Avatar asked Feb 02 '19 13:02

oezguensi


1 Answers

The syntax you have works just fine. I suspect the problem is the value of height. I suspect it isn't working because you are specifying an integer like 200 rather than a valid CSS height string like 200px.

Here's a simple example that works:

import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";

const Styled = styled.div`
  height: ${props => props.height};
  background-color: blue;
  color: white;
`;

function App() {
  return (
    <Styled className="App" height="200px">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </Styled>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit 945v7xjw1w

like image 170
Ryan Cogswell Avatar answered Dec 14 '22 08:12

Ryan Cogswell