본문 바로가기
Front-End/React

[React] 10. 조건부 렌더링

by hongdor 2021. 2. 3.
728x90

출처: React 공식 홈페이지

State 끌어올리기 – React (reactjs.org)

 

 

1. 데이터 변경사항을 주위 컴포넌트에 전파해야할 때

> 상위 컴포넌트로 state를 끌어 올리면 편리하다.
> 주어진 온도에서 물의 끓는 여부를 추정하는 온도 계산기를 만들어 볼 것이다.

 

 

2. Calcultor 컴포넌트를 만든다.

function BoilingVerdict(props){
  if(props.celsius >= 100){
    return <p>The water would boil.</p>
  }
  return <p>The water would not boil.</p>
}

class Calculator extends React.Component{
  constructor(props){
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {temperature: ''};
  }

  handleChange(e){
    this.setState({temperature: e.target.value});
  }

  render(){
    const temperature = this.state.temperature;
    return(
      <fieldset>
        <legend>Enter temperature in Celsius:</legend>
        <input
          value={temperature}
          onChange={this.handleChange}/>
        <BoilingVerdict
          celsius={parseFloat(temperature)}/>
      </fieldset>
    )
  }
}

ReactDOM.render(
  <Calculator/>,
  document.getElementById('root')
)

 

 

3. 새 요구사항으로 화씨 입력 필드 추가 요구

> 2개의 input을 만든다.

const scaleNames = {
  c: 'Celsius',
  f: 'Fahrenheit'
};

class TemperatureInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {temperature: ''};
  }

  handleChange(e) {
    this.setState({temperature: e.target.value});
  }

  render() {
    const temperature = this.state.temperature;
    const scale = this.props.scale;
    return (
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}:</legend>
        <input value={temperature}
               onChange={this.handleChange} />
      </fieldset>
    );
  }
}

class Calculator extends React.Component {
  render() {
    return (
      <div>
        <TemperatureInput scale="c" />
        <TemperatureInput scale="f" />
      </div>
    );
  }
}

ReactDOM.render(
  <Calculator />,
  document.getElementById('root')
);

 

 

4. 섭씨 화씨 변환 함수 작성

function toCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5 / 9;
}

function toFahrenheit(celsius) {
  return (celsius * 9 / 5) + 32;
}

 

 

5. 변환 함수를 포함하는, 숫자 검증 후 반올림하여 문자열로 반환하는 함수

function tryConvert(temperature, convert) {
  const input = parseFloat(temperature);
  if (Number.isNaN(input)) {
    return '';
  }
  const output = convert(input);
  const rounded = Math.round(output * 1000) / 1000;
  return rounded.toString();
}

 

 

6. State 끌어올리기

class TemperatureInput extends React.Component{
	constructor(props){
	super(props);
	this.handleChange = this.handleChange.bind(this);
	this.state = {temperature: ''};
	}

	handleChange(e){
		this.setState({temperature: e.target.value});
	}
	
	render(){
		const temperature = this.state.temperature;
		/...
	}
}

 

 

7. 하위 컴포넌트들이 props로 값을 받도록 변경


(1) TemperatureInput 컴포넌트

render() {
    // Before: const temperature = this.state.temperature;
    const temperature = this.props.temperature;
    // ...


(2) 부모 state 조작을 위해 onTemperatureChange 메서드를 props로 부모로부터 건네받는다.

handleChange(e) {
    // Before: this.setState({temperature: e.target.value});
    this.props.onTemperatureChange(e.target.value);
    // ...


(3) TemperatureInput 컴포넌트 완성

class TemperatureInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }

  render() {
    const temperature = this.props.temperature;
    const scale = this.props.scale;
    return (
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}:</legend>
        <input value={temperature}
               onChange={this.handleChange} />
      </fieldset>
    );
  }
}

7. 부모 컴포넌트의 state 로직 완성
class 

 

 

8. 부모 컴포넌트의 state 로직 완성

class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
    this.state = {temperature: '', scale: 'c'};
  }

  handleCelsiusChange(temperature) {
    this.setState({scale: 'c', temperature});
  }

  handleFahrenheitChange(temperature) {
    this.setState({scale: 'f', temperature});
  }

  render() {
    const scale = this.state.scale;
    const temperature = this.state.temperature;
    const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
    const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

    return (
      <div>
        <TemperatureInput
          scale="c"
          temperature={celsius}
          onTemperatureChange={this.handleCelsiusChange} />
        <TemperatureInput
          scale="f"
          temperature={fahrenheit}
          onTemperatureChange={this.handleFahrenheitChange} />
        <BoilingVerdict
          celsius={parseFloat(celsius)} />
      </div>
    );
  }
}

 

 

9. 완성 코드

const scaleNames = {
  c: 'Celsius',
  f: 'Fahrenheit'
};

function toCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5 / 9;
}

function toFahrenheit(celsius) {
  return (celsius * 9 / 5) + 32;
}

function tryConvert(temperature, convert) {
  const input = parseFloat(temperature);
  if (Number.isNaN(input)) {
    return '';
  }
  const output = convert(input);
  const rounded = Math.round(output * 1000) / 1000;
  return rounded.toString();
}

function BoilingVerdict(props) {
  if (props.celsius >= 100) {
    return <p>The water would boil.</p>;
  }
  return <p>The water would not boil.</p>;
}

class TemperatureInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }

  render() {
    const temperature = this.props.temperature;
    const scale = this.props.scale;
    return (
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}:</legend>
        <input value={temperature}
               onChange={this.handleChange} />
      </fieldset>
    );
  }
}

class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
    this.state = {temperature: '', scale: 'c'};
  }

  handleCelsiusChange(temperature) {
    this.setState({scale: 'c', temperature});
  }

  handleFahrenheitChange(temperature) {
    this.setState({scale: 'f', temperature});
  }

  render() {
    const scale = this.state.scale;
    const temperature = this.state.temperature;
    const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
    const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

    return (
      <div>
        <TemperatureInput
          scale="c"
          temperature={celsius}
          onTemperatureChange={this.handleCelsiusChange} />
        <TemperatureInput
          scale="f"
          temperature={fahrenheit}
          onTemperatureChange={this.handleFahrenheitChange} />
        <BoilingVerdict
          celsius={parseFloat(celsius)} />
      </div>
    );
  }
}

ReactDOM.render(
  <Calculator />,
  document.getElementById('root')
);

 

 

10. 교훈

> 동기화를 위해서는 하향식 데이터 흐름을 추천한다.
  장점으로 버그를 더 찾기 쉽다. state가 1개의 컴포넌트에 모여 있으므로 경우의 수가 적기 때문이다.
  또한 계산하는 로직들은 render() 에 넣고, state에는 본래의 값을 저장하는 것을 추천한다.
  왜냐하면 여러 로직들이 본래의 값에 기반해야 신뢰성을 높일 수 있다.

728x90

'Front-End > React' 카테고리의 다른 글

[React] 12. React로 사고하기(마지막)  (0) 2021.02.03
[React] 11. 합성 vs 상속  (0) 2021.02.03
[React] 9. 폼  (0) 2021.02.03
[React] 8. 리스트와 Key  (0) 2021.02.03
[React] 7. 조건부 렌더링  (0) 2021.02.01

댓글0