Hello stackoverflowers
I was wondering if it's possible to get the value of a styled-component
props into a javascript variable.
Example
<CardBox Columns="3">
What I wanted to do is :
var Columns = props => props.Columns;
var ColumnCount;
for (var i = 0; i < Columns; i++) {
ColumnCount = ColumnCount + "Auto ";
}
const CardBox = styled.div`
display: grid;
grid-template-columns: ${ColumnCount};
`;
But the variable Columns seems to be set to :
function (props) {
return props.Columns;
}
And not '3' as I hoped :)
Hope somebody can guide me in the right direction, if possible.
so what you are trying to accomplish is totally normal and a lot of people try to use.
You mainly try to pass properties like this:
const CardBox = styled.div`
width: 100px;
margin: 10px;
background: blue;
height: ${props => props.columns}px; <-- as an example if we need pixels
//we use props named columns as you will see below
`;
<CardBox columns={i} /> <-- how you pass to a styled component
In your case you will probably need to loop all your components and pass the parameter as you were doing and just render it, everything should be fine.
I made a simple codesanbox to try it out: https://codesandbox.io/s/21v3ql84kj
If you want a documentation part of property passing: https://www.styled-components.com/docs/basics#passed-props
Good luck!