ReasonJun

React : React.Component / Component (class) 본문

Frontend/React

React : React.Component / Component (class)

ReasonJun 2023. 6. 11. 02:11
728x90

React.Component / Component

 

In React, a class is a way to define a component using ES6 class syntax. It allows you to create reusable components with encapsulated state and behavior. React class components are based on the JavaScript class keyword and are an alternative to functional components.

 

To define a class component in React, you typically extend the base Component or **React.Component** class provided by the React library and implement the render() method. The render() method is responsible for defining the structure and content of the component's UI, which is returned as JSX (JavaScript XML).

 

Here's an example of a simple class component in React:

import React, { Component } from 'react';

class MyComponent extends Component {
  render() {
    return <div>Hello, World!</div>;
  }
}

// or

import React from 'react';

class MyComponent extends React.Component {
  render() {
    return <div>Hello, World!</div>;
  }
}

In the above example, MyComponent is a class component that extends React.Component. It defines a render() method that returns JSX representing the component's UI. In this case, it renders a div element with the text "Hello, World!".

 

By extending React.Component, you can leverage the various lifecycle methods provided by React, such as componentDidMount(), componentDidUpdate(), and componentWillUnmount(), to perform actions at specific stages of a component's lifecycle. You can also manage component state using this.state and update it using this.setState().

 

However, it's important to note that with the introduction of React Hooks in newer versions of React, functional components with hooks have become the recommended approach for most use cases. Hooks provide a simpler and more concise way to work with state and lifecycle events in functional components.

import React from 'react';

class MyComponent extends React.Component {
// state 생성
  constructor(props) {
    super(props);
    this.state = {
      message: 'Hello, World!'
    };
  }

handleClick() {
// state 변경
    this.setState({ message: 'Button clicked!' });
  }

  render() {
    return (
      <div>
        <p>{this.state.message}</p> // state 이용
        <button onClick={() => this.handleClick()}>Click me</button>
      </div>
    );
  }
}

Why pass props as arguments to super in React?

  • Pass props to the parent component to initialize the props property when a React.Component object is created.
  • To ensure that this.props can be used normally even inside the constructor.
import React from 'react';
// Inside React

class Component {
  constructor(props) {
    this.props = props;
  }
}

// Inside your code
class Button extends React.Component {
  constructor(props) {
    super(); // forgot to pass props
    console.log(props); // {}
    console.log(this.props); // undefined
  }
}

class Button extends React.Component {
  constructor(props) {
    super(props); // forgot to pass props
    console.log(props); // {}
    console.log(this.props); // {}
  }
}

Keep state in parent component

To aggregate data from multiple children or to have two child components communicate with each other, you must define a shared state in the parent component. Parent components can pass state back to child components using props.

This makes child components synchronize with each other or with the parent component.

// You can create a React class component with the rcc command. (based on filename)
import React, { Component } from 'react';
import Square from './Square';
import './Board.css';

export default class Board extends Component {
  constructor(props) {
    super(props);
   // Use state to remember something.
    this.state = {
      squares: Array(9).fill(null),
    };
  }

  renderSquare(i) {
    return <Square value={this.state.squares} />;
  }

  render() {
    return (
      <div>
        <div className='status'>Next Player: X, O</div>
        <div className='board-row'>
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className='board-row'>
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className='board-row'>
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}
import React from 'react';
import './Square.css';

export default class Square extends React.Component {
  // Props are a way to pass data from an inheriting parent component to a child component.
 // Props are read-only and do not change from the point of view of child components. (If you want to change it, you must change the state in the parent component.)

  render() { 
    return (
      <button
        className='square'
        onClick={() => {
          // change state 
          this.setState({ value: 'X' });
        }}
      >
        {/* use state */}
        {this.props.value}
      </button>
    );
  }
}
728x90

'Frontend > React' 카테고리의 다른 글

React : SPA  (1) 2023.06.11
React : lifecycle  (0) 2023.06.11
React : state / props  (0) 2023.06.11
React : Basic Rules for JSX  (0) 2023.06.11
React : JSX (JavaScript XML)  (0) 2023.06.11
Comments