본문 바로가기
💻CODING/react. vue

[react] react에서 inline style 적용 방법 (ft. 인라인 css)

by 코딩하는 갓디노 2021. 12. 22.

[react] react에서 inline style 적용 방법 (ft. 인라인 css)

 

react에서 inline style(inline css)
적용 방법입니다.

 

인라인 스타일 방식은 태그 내에 자바스크립트 객체 형식으로 직접 넣는 스타일 방식입니다.

 

react inline style 적용 방법

예제1

가장 보편적으로 쓰이는 태그 내 스타일 전체 삽입 방법입니다.

<div style={{ display:'inline-block', width:'200px', height:'200px'}}></div>

 

예제2

변수를 이용하여 스타일을 적용한 방법입니다. 

import React from 'react';

const SingIn = () => {
    const leftIcon = { backgroundImage: "url('/images/homebar.svg')" };
    
    return (
        <div style={leftIcon}></div>
    );
};

export default SingIn;

 

예제3

리렌더링 방지를 위해 PureComponent로 감싸주었고, 분기 처리 된 인라인 스타일 적용 예제입니다.

import React, { PureComponent} from 'react';
class Ball extends PureComponent {
  render() {
    let background;
    const { number } = this.props;
    if (number < 10) {
      background = 'yellow';
    } else if (number < 20) {
      background = 'aqua';
    } else if (number < 30) {
      background = 'pink';
    } else if (number < 40) {
      background = 'skyblue';
    } else {
      background = 'gold';
    }
    return ( <><div className = 'ball' style = {{background}}> { number } </div></> )
  }
}
export default Ball;

 

예제4

style={Object.assign({}, a, b)}를 이용하여 서로 다른 두개의 객체 데이터를 하나의 객체로 합쳐 사용하였습니다.

class App extends Component {
  state = {
    disabled: true,
  }
  onChange = (e) => {
    const length = e.target.value.length;
    if (length >= 4) {
      this.setState(() => ({ disabled: false }))
    } else if (!this.state.disabled) {
      this.setState(() => ({ disabled: true }))
    }
  }
  render() {
    const label = this.state.disabled ? 'Disabled' : 'Submit';
    return (
      <div className="App">
        <button
          style={Object.assign({}, styles.button, !this.state.disabled && styles.buttonEnabled)}
          disabled={this.state.disabled}
        >{label}</button>
        <input
          style={styles.input}
          onChange={this.onChange}
        />
      </div>
    );
  }
}

const styles = {
  input: {
    width: 200,
    outline: 'none',
    fontSize: 20,
    padding: 10,
    border: 'none',
    backgroundColor: '#ddd',
    marginTop: 10,
  },
  button: {
    width: 180,
    height: 50,
    border: 'none',
    borderRadius: 4,
    fontSize: 20,
    cursor: 'pointer',
    transition: '.25s all',
  },
  buttonEnabled: {
    backgroundColor: '#ffc107',
    width: 220,
  }
}

출처: https://medium.com/react-native-training/react-animations-in-depth-433e2b3f0e8e 

 

예제5

useMemo를 사용한 방법입니다.

import React, { useMemo } from 'react';

const Home = () => {
    const bgImg = useMemo(() => ({ backgroundImage: "url('/images/mobile/home/map.svg')" }), [])

    return (
        <div style={bgImg}></div>
    );
};

export default Home;

 

react inline style 문제점

React는 jsx 문법 사용으로 이루어져있고, jsx는 React.createElement(…)를 통하여 변환이 되고,
모든 속성이 props 객체의 부분이 됩니다. 

inline style에서 ({} === {} //결과 false) 렌더링시 inline style에서 사용한 {} 는 이전 값과 비교하였을 때 false가 나와 
매번 다시 리랜더링을 일으키게 됩니다.
이것이 규모가 커진 앱일수록 성능 저하를 일어납니다 .

 

React 공식문서에서도 using style attribute as the primary means of styling elements is generally no recommended 라고 나와있습니다.  

리랜더링을 방지하기 위해 위의 예제 3번과 같이 PureComponent 또는 useMemo를 이용해 한번 감싸주어 랜더링을 최소화 시켜 리랜더링 문제를 최적화 할 수 있습니다.

반응형

댓글