0

I try to pass a variable in a component that uses styled-components

This is how I call the component

<td><p><LimitBar width = {perc}/> {perc}%</p></td> 

perc is a number between 0 and 100

Then, the LimitBar is like this

const LimitBarBorder = styled.span` ...some css `; const LimitBarColored = styled.span` ...some more css width: ${props => props.width}; `; const LimitBar = (width) => ( <LimitBarBorder> <LimitBarColored width={width}></LimitBarColored> </LimitBarBorder> ); export default LimitBar; 

But, then, the HTML code is like this

<td> <p> <span class="sc-pHKzq izKVhe"> <span width="[object Object]" class="sc-pQFoF bkUWrD"></span> </span> 85% </p> </td> 

As you can see, the width parameter passed as object, while it is just a number. I am new on React and try to do it with online tutorials and official documentations.

2 Answers 2

1
const LimitBar = ({width}) => ( <LimitBarBorder> <LimitBarColored width={width}></LimitBarColored> </LimitBarBorder> ); export default LimitBar; 

It doesn't look like you're passing in the prop correctly.

Sign up to request clarification or add additional context in comments.

7 Comments

Now, I get <span width="85" class="sc-pQFoF dsLEU"></span> without applying the CSS rule.
What css rule if I may ask? Because your question was how to pass in the variable.
It is in the question. Sorry if wasn't clear width: ${props => props.width};
how are you able to tell that the width of 85 on the span element is not being applied?
Actually, that is the problem. Changing it to width: ${props => props.width + '%'};, together with the changed in your answer, fixed the problem
|
0

On this line:

width: ${props => props.width}; 

You are setting the width to be equal to the function that takes props as parameter and returns props.width. To fix, just insert props.width instead:

width: ${props.width}; 

Edit: Also see Jonathan's answer and adjust your function component accordingly.

2 Comments

With or without the Jonathan's change, changing the width as you suggest raises this error on console props is not defined
@Tasos What about this.props.width ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.