렌더링 -> HTML MARKUP -> DOM -> 브라우저 화면
컴포넌트에서 데이터의 변화가 발생하면 뷰가 변형되는 게 아닌 새로운 요소로 갈아 끼우는데 이 액션도 render()가 진행됩니다. 새로운 데이터로 render()가 다시 실행된다는 의미!
import React from 'react';
function App() {
const name = '리액트'; //리앸트
return(
<div>
{name === '리액트' ? (<p>IS-REACT</p>)
: ( <p>IS-NOT-REACT</p> )
);
}
export default App;
JSX 내부 주석
{/ 주석 /}
외부 부석
// 한줄 주석
/ 주석 /
예)
// MyComponent.js
import React from 'react';
const MyComponent = props -> {
return <div>이름은 : {props.name}</div>;
};
export default MyComponent;
//App.js
import React from 'react';
import MyComponent from './MyComponent';
const App = () =>{
return <MyComponent name = "ReactName"/>;
};
export default App;
//RESULT
이름은 : ReactName
import React, {Component} from 'react';
class Counter extends Component {
constructor(props){
super(props);
this.state = { number : 0 };
};
render(){
const { number } = this.state;
return (
<h1>{number}</h1>
<button onClick = { () => {
this.setState ({ number : number +1 });
}}>
);
};
export default Counter;
import React, {useState} from 'react';
import axios from 'axios';
const App = () => {
const [data, setData] = useState(null);
const onClick = async () =? {
try {
const response = await axios.get(
'https://newsapi.org/ve/top-headlines?country-kr&apiKey=key',);
setData(response.data);
} catch(e){
console.log(e);
}
};
return(
<button onClick= {onClick}> 불러오기</button>
{data && <textarea rows = {7} value = {JSON.stringify(data, null, 2) } /> }
);
};
export default App;
const array = [1,2];
const one = array[0];
const two = array[1];
-->
const array = [1,2];
const [one, two] = array;
import React, {ustState} from 'react';
const Say = () => {
const [message, setMessage] = useState('');
const onClickEnter = () => setMessage('hi');
const onClickLeave = () =>
setMessage('bye');
return (
<button onClick = {onClickEnter}>Hi</button>
<button onClick = {onClickLeave}>Leave</button>
<h1>{message}</h1>
);
};
};
export default Say;
Components: Building blocks of a React application that encapsulate functionality and UI, making them reusable and maintainable.
function HelloWorld() {
return <p>Hello, World!</p>;
}
// Usage: <HelloWorld />
JSX: A syntax extension for JavaScript that allows you to write HTML-like code within your JavaScript code, making it easier to create and manage UI elements.
State: An object within a component that holds data specific to that component and affects its rendering.
class App extends React.Component {
state = {
message: 'Hello React!'
};
render() {
return <div>{this.state.message}</div>;
}
}
// or using hooks in functional components
function App() {
const [message, setMessage] = React.useState('Hello React!');
return <div>{message}</div>;
}
Props: A way to pass data and callbacks from a parent component to a child component, allowing for one-way communication and data flow.
function Greeting(props) {
return <p>Hello, {props.name}!</p>;
}
// Usage: <Greeting name="John" />
Functional Components: Stateless components that accept props and return a JSX element. They are more lightweight and often used for presentational components.
import React from 'react';
function FunctionalComponent(props) {
return <div>Hello, {props.name}!</div>;
}
// Usage: <FunctionalComponent name="John" />
Class Components: Components that have their own state and lifecycle methods. These components are more complex and suited for stateful components.
import React, { Component } from 'react';
class ClassComponent extends Component {
render() {
return <div>Hello, {this.props.name}!</div>;
}
}
// Usage: <ClassComponent name="John" />
useState Hook: A way to add state to functional components, making it possible to manage state without using class components.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
// Usage: <Counter />
useEffect Hook: A way to manage side effects, such as data fetching or subscriptions, in functional components.
import React, { useState, useEffect } from 'react';
function FetchData() {
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
setIsLoading(false);
};
fetchData();
}, []);
return (
<div>
{isLoading ? (
'Loading...'
) : (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
)}
</div>
);
}
// Usage: <FetchData />
Conditional Rendering: A technique to render different UI elements based on certain conditions, like the state or props of a component.
function App() {
const isVisible = true;
return <div>{isVisible && 'Conditional Text'}</div>;
}
Lists and Keys: A way to render collections of items in React by mapping over an array and using unique keys for each element.
function App() {
const items = [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' }
];
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.text}</li>
))}
</ul>
);
}
Event Handling: Managing user interactions, such as clicks, keyboard input, or form submissions, using event handlers and callbacks.
class App extends React.Component {
handleClick() {
console.log('Button clicked');
}
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}
// or using hooks in functional components
function App() {
const handleClick = () => {
console.log('Button clicked');
};
return <button onClick={handleClick}>Click Me</button>;
}
Controlled Components: Form components whose state is managed by React, making it easier to handle form input and validation.
class App extends React.Component {
state = {
inputValue: ''
};
handleChange = event => {
this.setState({ inputValue: event.target.value });
};
render() {
return <input value={this.state.inputValue} onChange={this.handleChange} />;
}
}
// or using hooks in functional components
function App() {
const [inputValue, setInputValue] = React.useState('');
const handleChange = event => setInputValue(event.target.value);
return <input value={inputValue} onChange={handleChange} />;
}
Lifting State Up: A technique to manage shared state between components by placing the state in a common ancestor component.
function Parent() {
const [value, setValue] = React.useState('');
return (
<>
<Child1 value={value} />
<Child2 setValue={setValue} />
</>
);
}
function Child1(props) {
return <div>Value: {props.value}</div>;
}
function Child2(props) {
return <input value={props.value} onChange={e => props.setValue(e.target.value)} />;
}
Higher-Order Components (HOCs): A way to reuse component logic by wrapping one component within another component.
React Context API: A mechanism to share global state or pass data through the component tree without using props drilling.
React Router: A popular library for handling client-side routing in React applications, enabling navigation between different components based on URL changes.
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
Code Splitting: A technique to break your application into smaller chunks, improving performance and reducing the initial load time.
Server-side Rendering (SSR): A technique to pre-render React applications on the server, improving performance and search engine optimization (SEO).
React Performance Optimization: Techniques to optimize the performance of your React application, such as using PureComponent, React.memo, and useCallback.
리액트를 다루는 기술 - 김민준