Intro to React.js
How does React.js work
- React uses JavaScript to creates all the elements you write and pushes them to HTML.
- Virtual DOM is used. It's a fast and lightweight copy.
Component in React.js
- Component is parts of reusable and independent code in React.js.
- It does serve like JavaScript functions, but it returns HTML.
- When you create React app or show data from React, you deal with Component to make the React application works.
- DOM is case sensitive, so Component should start with a capital letter.
Example Code
index.js
import React from 'react';
function App() {
return <div>Hello</div>;
}
export default App;
|
App.js
import React from 'react';
function App() {
return <div>Hello</div>;
}
export default App;
|
Component is just a function returns HTML. This combination of JavaScript and HTML is called JSX.
JSX
- JSX is only specific to React. Javascript와 html사이의 조합. react에만 있는 유일한 개념
- JSX is a shorthand for JavaScript XML.
- The easier way to write Javascript in the browser and its easy to understand.
- We declare a variable called name and then use it inside JSX by wrapping it in curly braces.
Making own component
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
|
App.js
import React from 'react';
import MyComponent from './MyComponent';
function App() {
return (<div>Hello
<MyComponent />
</div>)
}
export default App;
|
MyComponent.js
import React from 'react';
function MyComponent(){
return <div>My first component</div>;
}
export default MyComponent;
|
React application should render one component. MyComponent component can not be located in index.js with App.js.
Its should be inside of App.js
Works fine
Prop
- Stands for property
- Used to pass data from component to another component
- Sharing code technique between React component is called 'Render prop'
import React from 'react';
function Prop({name, pic}){
return <div>
<h2>my {name} favorite </h2>
<img src = {pic}></img>
</div>;
}
const myFav = [
{name:"first",
image:"http://usapple.org/wp-content/uploads/2016/02/apple-red-delicious-337x335.png" },
{name:"second",
image: "https://images-na.ssl-images-amazon.com/images/I/71gI-IUNUkL._SY355_.jpg"}];
function App() {
return (
<div>
<h1>My favorites</h1>
{myFav.map(fav => (
<Prop name={fav.name} pic={fav.image}/>
))}
</div>);
}
export default App;
|
Result
State
- state let components to create and modify their own data.
- to change state, use setState()
Reference
https://www.freecodecamp.org/news/react-js-for-beginners-props-state-explained/