React

Function Components

WebDevLee 2021. 12. 5. 22:41

이 글은 React의 2가지 컴포넌트 중 함수 컴포넌트에 대한 개념을 정리하기 위해 작성하였습니다.




< Functional Components >

In the latest versions of React, function components can do everything that class components can do.
In most cases, however, function components offer a more elegant, concise way of creating React components.


 

Example)

// A class component class:
export class MyComponentClass extends React.Component {
  render() {
    return <h1>Hello world</h1>;
  }
}

// The same functional component:
export const MyComponentClass = () => {
  return <h1>Hello world</h1>;
}

// Works the same either way:
ReactDOM.render(
	<MyComponentClass />,
	document.getElementById('app')
);

: To convert class component to function component, all you need to do is remove the beginning  render( ) {  and ending  }  of the render( ) method

 

 


< Function Components and Props >

Like any component, function components can receive information via props.

To access these props, give your function component a parameter named props.

 

Example)

import React from 'react';
import ReactDOM from 'react-dom';

export const NewFriend = (props) => {
  return (
    <div>
      <img src={props.src} />
    </div>
  );
}

ReactDOM.render(
  <NewFriend src="https://content.codecademy.com/courses/React/react_photo-squid.jpg" />,
  document.getElementById('app')
);