tdlanghe
tdlanghe

Reputation: 35

Internal styling in React

I would have assumed that this would have been easy for me to find but I can't find it anywhere. In HTML you can style all your tags (headers, paragraphs, img, etc.) like this:

<style>
  body {background-color: powderblue;}
  h1   {color: blue;}
  p    {color: red;}
</style>

How do I do the same in React? I want to reference all p tags and some custom ones from classes.

Upvotes: 1

Views: 4574

Answers (2)

Hemadri Dasari
Hemadri Dasari

Reputation: 34014

In react it would be something like below. you use style prop to apply inline styles and in react background-color is backgrounColor.

To apply same style for all p tags, h1 tags and body you use same .css file and you put all css styles into .css file and the css file has to be imported in parent component so that the style you have in .css file will be applied. Something like below

app.css

body {background-color: powderblue;}
h1   {color: blue;}
p    {color: red;}

App.js component

 import "./app.css";//so the styles will be applied to body and all h1 and p tags as global

Below are few inline style examples of react Note: is neither a string nor HTML, It is called JSX, and it is a syntax extension to JavaScript. Doc here

<body style={{backgroundColor: "powderblue"}}>
   <h1 style={{color: "blue"}}> </h1>
   <p style={{color: "red"}}></p>
 </body>

OR

render(){
   const style= {colorBlue: "blue", colorRed: "red"};

   return(
      <div>
         <h1 style={{color: style.colorBlue}}> </h1>
         <p style={{color: style.colorRed}}></p>
       </div>
   )
}

Upvotes: 1

Agustin Meriles
Agustin Meriles

Reputation: 4854

ReactJs is just a javascript framework, that "runs" on an HTML page. So, if you want to add those style definitions globally, you can include them in the head section of your master layout page or container page, the one that contains the "root" react component.

 <html>
 <head>
 <style>
    body {background-color: powderblue;}
    h1   {color: blue;}
    p    {color: red;}
</style>
<!-- your other css and javascript definitions, including probably react -->
</head>
<body>
    <MyReactComponent />
</body>
</html>

Upvotes: 0

Related Questions