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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With