React

Style

WebDevLee 2021. 12. 6. 23:57

이 글은 React에서의 스타일 적용(CSS사용)에 대한 개념을 정리하기 위해 작성하였습니다.




< Inline Styles >

There are many different ways to use styles in React.

An inline style is a style that’s written as an attribute.

 

Example)

<h1 style={{ color: 'red' }}>Hello world</h1>

: Notice the double curly braces.

  1. The outer curly braces inject JavaScript into JSX.
  2. The inner curly braces create a JavaScript object literal.

 

 


< Make A Style Object Variable >

To use styles in React.

 

Example)

const styles = {
  color: 'darkcyan',
  background: 'mintcream'
};
<h1 style={styles}>Hello world</h1>

 

 


< Style Name Syntax >

In regular JavaScript, style names are written in hyphenated-lowercase :
const styles = {
  'margin-top': '20px',
  'background-color': 'green'
};​

In React, those same names are instead written in camelCase :
const styles = {
  marginTop: '20px',
  backgroundColor: 'green'
};

 

 


< Style Value Syntax >

In React, if you write a style value as a number, then the unit "px" is assumed.
// If you want a font size of 30px
{ fontSize: 30 }

// If you want to use units other than “px"
{ fontSize: "2em" }​