javascriptcssreactjs

How to pass inline style with props in react js?


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 ?


Solution

  • 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>;