React Summary of Ways to Create Components
- 2021-12-04 17:54:17
- OfStack
1. Create a component using a function
Function components: Components created using JS functions (or arrow functions)
Convention 1: Function names must begin with uppercase letters
Convention 2: A function component must have a return value that represents the structure of the component
If the return value is null, nothing is rendered
function Hello() {
return (
<div> This is my first 1 Function components! </div>
)
}
const Hello = () => <div> This is my first 1 Function components! </div>
Render function component: Use function name as component label name
Component labels can be single labels or double labels
//1. Import react
import React from 'react';
import ReactDOM from 'react-dom';
/*
Function component:
*/
function Hello() {
return (
<div> This is my first 1 Function components! </div>
)
}
// Rendering component
ReactDOM.render(<Hello />, document.getElementById('root'))
2. Create components using classes
Component class: Components created using class of ES6
Convention 1: Class names must also begin with uppercase letters
Convention 2: Class components should inherit from the React. Component parent class so that they can use the methods or properties provided in the parent class
Convention 3: Class components must provide render () method
Convention 4: The render () method must have a return value representing the structure of the component
//1. Import react
import React from 'react';
import ReactDOM from 'react-dom';
/*
Function component:
*/
function Hello() {
return (
<div> This is my first 1 Function components! </div>
)
}
// Rendering component
ReactDOM.render(<Hello />, document.getElementById('root'))
3. Extract as a stand-alone JS file
1. Create Hello. js
2. Import React into Hello. js
3. Create a component (function or class)
4. Export the component in Hello. js
5. Import Hello components in index. js
6. Render components
Hello.js
import React from "react";
// Create a component
class Hello extends React.Component {
render () {
return (
<div> This is my first 1 A pull away to js Components in the file! </div>
)
}
}
// Export component
export default Hello
index.js
//1. Import react
import React from 'react';
import ReactDOM from 'react-dom';
/*
Pull the component to a separate JS In the file:
*/
// Import Hello Component
import Hello from './Hello';
// Rendering component
ReactDOM.render(<Hello />, document.getElementById('root'))