Basic
What I see and study?
NomadCoders provides Lecture for React.
So, I note this post what I study.
Please see this lecture if you study react.
Language
class App extends Component {
render() {
return (
<div className="App">
</div>
);
}
}React uses JSX that made by facebook.
So, We can use html in JS.
Distribute
npm run start is starting way for developer.
npm run build is building way for user.
It makes build directory.
Built index.html is in build directory.
Easy web server
npm install -g serve webserver install.
npx serve -s build is build directory makes document root.
Actually, create-react-app provides npm start that development server,
Local is local server and ‘On Your Network’ is Wi-fi server that can be shared.
this server is automatically fixed.
Ect
manifest.json in the public is PWA.
React
Good of React
React is used by almost JS.
So, even If react disappeares, We will use JS.
It has safety.
Execute
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();<App /> is made by react.
App from import App from './App';. It is ./App.js actually.
document.getElementById('root')); makes <App> tag in index.js in Id ‘root’
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</App>
</header>
</div>
);
}
export default App;This code is App.js that functional type.
This note is class type.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;React inserts Component js into ElementbyID
When Application loads empty html in index.html,
React sinserts html in div.
Tag
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));This is index.js code.
import Tagname from './file'; // './file.js';
ReactDom.render(<Tagname />, document.getElementById('root));
Insert contents of file in index.html in public folder to what has tagname Id.
Component
class Tagname extends Component {
render() { // Method of Component that view html.
return ( // function render's return that is written html.
<div className="Tagname"> // <header>
</div> // </header>
}
}fuction Tagname() {
return (
<div className="Tagname">contents
</div>
)
}Component must start one of top-ranked tag
like <header> or `<div className="Tagname">
We can use maked Component in another Component.
Two code is same but different form.
1st is class Component, 2nd is function Component.
React automatically execute class component’s render method.
<div className="App">
<Tagname></Tagname>
</div>Like this.
Component is function that returns HTML.
Component’s form is <Tagname></Tagname> same <Tagname />
React application can render one component once.
So, insert Tagname in App.js
JSX and Props
JSX is JS + HTML
JSX can makes recyclable component.
JSX transfer can data to component.
How to?
function Movie(props) { {/* props => {movname} is also OK */}
console.log(props) {/* Object that has movname: "21" */}
console.log(props.movname) {/* value of movname => 21 <- ES6 Syntax */}
return <h2>Movie name : {props.movname}</h2>
}
function App() {
return (
<div className="App">
<h1>Hello</h1>
<Movie movname="21"></Movie> {/* For recycle */}
<Movie movname="Find lost world"></Movie>
</div>• <Movie movname="21"></Movie> • => We transfer the property '21' that has name 'movname' to Movie component
• It also can be string={value} and take multiple props. • Props is property.
• Props can be used by react magic that takes props. (arguments form)
• We can use movname property by 'props.movname'. ( on code ) • Use components dynamically.
Dynamic Component
Suppose Data is transfered by API.
So, we can make function that use data.
What we use? map
Map is similar to foreach. array.map(arg => {console.log(arg); return 0})
Map takes function and apply function each items in array.
Arg name is free and map’s return value be a array.
It is ES6 Syntax ( => arrow function )
If you wan’t old JS, array.map(function(arg) { contents })
function Movie(props) {
return <div className="MovieCom">
<h2>Movie name : {props.name}</h2>
<img src={props.img} width="500px"></img>
</div>
}
const Moviename = [
{
name: "flower",
image: "https://i.imgur.com/XroHcwe.jpg"
},
{
name: "dark nebula",
image: "https://i.imgur.com/fMGVpco.jpg"
},
{
name: "Crystalized amino",
image: "https://i.imgur.com/yRlkwEc.jpg"
}
]
function App() {
return (
<div className="App">
<h1>Movie List</h1>
{Moviename.map(current =>
<Movie name={current.name} img={current.image}></Movie>
)}
{/* current is each items.*/}
</div>
);
}Code that is important part.
And It can be expressed the other code.
Map function
function Movie({name, image}) {
return <div className="MovieCom">
<h2>Movie name : {name}</h2>
<img src={image} width="500px"></img>
</div>
}
const Moviename = [
{
name: "flower",
image: "https://i.imgur.com/XroHcwe.jpg"
},
...
]
function renderMovie(mov) {
console.log(mov);
return <Movie name={mov.name} image={mov.image}></Movie>
}
function App() {
return (
<div className="App">
<h1>Movie List</h1>
{Moviename.map(renderMovie)}
</div>
);
}Like this.
First code is more simple and good.
This code’s console says warning.
Reason is Each child in a list should have a unique “key” prop
All of elements of React must be unique and
when we input its to list, they lost their uniqueness.
So, we need to add Id for seperation? in Moviename.
const Moviename = [
{
id : 1
name: "flower",
image: "https://i.imgur.com/XroHcwe.jpg"
},
...
]
function App() {
return (
<div className="App">
<h1>Movie List</h1>
{Moviename.map(mov => (
<Movie key={mov.id} name={mov.name} image={mov.image}></Movie>
))}
</div>
);
}We give key prop in Movie tag.
Then error is disappeared.
But, key is not used in Movie, so we don’t transfer it.
It is only used for React internal using.
Prop-types
We have to check props type.
When Movie wants image but you transfer picture.
This way, someone show you your componenet doesn’t work.
There is module for checking.
npm i prop-types
import PropTypes from 'prop-types';
function Movie({name, image, rating}) {
return <div className="MovieCom">
<h2>Movie name : {name}</h2>
<h3>{rating} / 5.0</h3>
<img src={image} width="500px" alt={name}></img>
</div>
}
Movie.propTypes = {
name: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
rating: PropTypes.number.isRequired
};Movie.propTypes checks is it a correct props?
and isRequired check values are transfered.
If image: PropTypes.string, this prop is string or undefined.
More information
State
State is used when we work with dynamic data (doesn’t-exist).
Dynamic data can’t be helped by props.
State is Object, and data is changed.
Input into state what you want to change data.
import React from 'react';
class App extends React.Component {
state = {
count: 0
};
add = () => {
console.log("add");
this.setState({count: this.state.count + 1});
// If you directly change state like this.state.count = 1;, doesn't work.
// why? react doesn't refresh render function.
};
subtract = () => {
console.log("subtract");
this.setState({count: this.state.count - 1});
};
render() {
return (
<div className="App">
<h1>Class Component</h1>
<p>State: {this.state.count}</p>
<button onClick={this.add}>Add</button> // this.add() <- imediately exec
<button onClick={this.subtract}>Subtract</button>
</div>
)
}
}When you call setState, React refresh render fundtion with new state.
This code is not good way using state like this.setState({count: this.state.count + 1});
Good way is this code.
Why? doens’t use state in setState.
add = () => {
console.log("add");
this.setState(current => ({ count: current.count + 1}));
};
subtract = () => {
console.log("subtract");
this.setState(current => ({ count: current.count + 1}));
};Life Cycle
Life Cycle Method is way that React create and remove component.
When component updates, some functions are called.
• Mounting: component born
• Updating: update
• Unmounting: component die(move page).
Mounting
• constructor : JS function that called when class is created. not React.
• getDerivedStateFromProps : refer official page.
• componentDidMount : when component render, use.
Update
• static getDerivedStateFromProps : refer official.
• shouldComponentUpdate : refer official. It is dicide that you update component.
• getSnapshotBeforeUpdate : refer official.
• componentDidUpdate : when component updated, exec.
componentDidMount() {
console.log("rendered");
}
componentDidUpdate() {
console.log("Updated");
}
componentWillUnmount() {
console.log("bye");
}Use way.
import React from 'react';
class App extends React.Component {
state = {
isLoading: true, // When page mount, loading.
movies: []
};
componentDidMount() {
setTimeout(() => {
this.setState({isLoading: false});
}, 5000); // not react. JS ES6.
} // after 5 seconds, isLoading is false.
render() {
const {isLoading} = this.state;
return (
<div className="App">
{isLoading ? "Loading...": "We are ready"} {/*this.state.isLoading*/}
</div>
)
}
}Axios
Axios is like layer on fetch.
When you use API, axios.get("URL");
getMovies = async() => { //async says 'we want little times.'
const movies = await axios.get("https://yts-proxy.now.sh/list_movies.json");
// await <- what you want to wait? (async 비동기)
console.log(movies.data.data.movies);
}
componentDidMount() {
this.getMovies();
}It can be more simple.
getMovies = async() => { //async says 'we want little times.'
const {
data: {
data: {movies}
}
} = await axios.get("https://yts-proxy.now.sh/list_movies.json");
// await <- what you want to wait? (async 비동기)
console.log(movies);
//this.setState({movies:movies})
this.setState({movies, isLoading: false})
}Use Component
If component doesn’t need state, use function style is better.
Movie Js
function Movie({ id, year, title, summary, poster }) {
return <h5>{title}</h5>;
}
Movie.propTypes = {
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
year: PropTypes.number.isRequired,
summary: PropTypes.string.isRequired,
poster: PropTypes.string.isRequired
};
export default Movie;App Js
render() {
const {isLoading, movies} = this.state;
return ( <div className = "App" >
{ isLoading ? "Loading..." : movies.map(movie => {
console.log(movie);
return (
<Movie
id={movie.id}
year={movie.year}
title={movie.title}
summary={movie.summary}
poster={movie.medium_cover_image}
/>
);
})}
</div>
);
}Styling
<h3 className="movie_title" style=qq backgroundColor: "red" pp>{title}</h3>
<h5 className="movie_year">{year}</h5>
You can use css on javaScript in this way.
But bad way, so create css file.