Reputation: 3806
I want to pass inline styles with props like this :
<P style={{marginTop : '20px'}}>{price}</P>
import React from 'react';
function P(props) {
return <p style={{ width: '100%', textAlign: 'right', fontSize: '1.3em' ,{props.style} }}>{props.children}</p>;
}
export default P;
But it throws an error in terminal saying :
Unexpected token, expected , (4:74)
2 |
3 | function P(props) {
> 4 | return <p style={{ width: '100%', textAlign: 'right', fontSize: '1.3em' {props.style} }}>{props.children}</p>;
| ^
5 | }
6 |
7 | export default P;
How can I pass inline styles with props to another component in react js ?
Upvotes: 0
Views: 3172
Reputation: 1
You can do something like this
<P style='{ "width": "100%", "textAlign": "right", "fontSize": "1.3em"}' price="10"></P>
and use it inside the function like this
function P(props: {style: any; price: string}) {
return <p style={{...JSON.parse(props.style)}}>{Number(props.price)}</p>;
}
Note that the properties inside style props SHOULD HAVE "", or else JSON.parse() function won't work.
Upvotes: 0
Reputation: 111
You should pass the style props like this:
function P(props) {
return <p style={{ width: '100%', textAlign: 'right', fontSize:'1.3em',...props.style }}>
{props.children}</p>;
}
Upvotes: 2
Reputation: 155
What you should do is, send the exact value of margin-top, rather than the css code, like so
<P marginT='20px'>{price}</P>
and using it like:
<p style={{ marginTop: this.props.marginT }}>{props.children}</p>;
Upvotes: 3