Fundamentals of React
Project Structure
- main.jsx injects the entire React application into the HTML index.html file, displaying it inside the
<div id="root">.
{/* index.html */}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My React App</title>
</head>
<body>
<div id="root"></div>
{/* This script will load the bundled JavaScript files created by React */}
<script type="module" src="/main.js"></script>
</body>
</html>
//main.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App'; // Importing the main App component
import './index.css'; // Importing global styles
// Find the 'root' div in index.html and attach the app to it
const root = ReactDOM.createRoot (document.getElementById ('root'));
// Render the <App /> component, which contains the main structure of the app
root.render (<App />);
// App.js
import React from 'react'; // Import the React library
import './App.css'; // Import styles specific to App component
// Define the App component
function App () {
return (
<div className="app-container">
<h1>Welcome to My React App!</h1>
<p>This is a simple example of a React component structure.</p>
</div>
);
}
// Export the App component so it can be used in other files
export default App;
npm Scripts
meet the react component
function App () {
return (
<div>
<h1>Hello React</h1>
</div> );
}
export default App;
react JSX-javaScriptXml
const title = 'React';
function App () {
return (
<div>
<h1>Hello {title}</h1>
</div> );
}
export default App;
Lists in React- map ()
- every React element in a list should have a key assigned to it. The key is an HTML attribute and should be a stable identifier.
<ul>
{list.map (function (item) {
return <li key={item.objectID}>{item.title}</li>;
})} </ul>
<ul>
{list.map (function (item){
return <a href={item.url}>{item.title}</a>
})}
</ul>
meet another react component
- Question: How do you decide when to extract a component? – Answer: Extract a component when you find repeated UI patterns or functionality within your code.
React DOM
- ReactDOM is a package in React used for rendering React components into the browser DOM
React Component Declaration
- //function declaration
function App () { ... }//arrow function expressionconst App = () => { ... }
- before
//with block body
const addOne = (count) => {
//perform any task in between
return count + 1
}
- after
//with concise body as one line
const addOne = (count) => count + 1
Handler Function in JSX
- for the change event of the input field. In React, this function is called an (event) handler.the function can be passed to the onChange attribute (JSX named attribute) of the HTML input field
// Define the handler function
const handleChange = (event) => {
console.log (event.target.value);
};
//if handleChange is a function
//which does not return a function
//don't do this
<input onChange={handleChange ()} />
//do this instead
<input onChange={handleChange} />
React Props
- Props (short for properties) are a mechanism for passing data from a parent component to a child component.
- Include them as attributes, like
<MyComponent prop1={value1} prop2={value2} />. Pass props to a component - props are immutable. They should be treated as read-only
React State
- React state introduces a mutable data structure
- By using useState, we are telling React that we want to have a stateful value which changes over time. 在 stateful 状态的变量会随着值的改变而进行实时的 render。
- const [value,setValue] = useState (’')
- useState is a React hook that allows function components to manage and update state.
- State changes or prop updates can trigger a re-render in React.
Callback Handlers in JSX
const App = () => {
const stories = [ ... ];
// A
const handleSearch = (event) => {
// D
console.log (event.target.value);
};
return (
<div>
<h1>My Hacker Stories</h1>
{/* // B */}
<Search onSearch={handleSearch} />
<hr />
<List list={stories} />
</div>
); };
const Search = (props) => {
const [searchTerm, setSearchTerm] = React.useState ('');
const handleChange = (event) => {
setSearchTerm (event.target.value);
// C
props.onSearch (event);
};
return ( ... );
};
Lifting State in React
- Lifting state refers to the practice of moving the state from a child component to its parent component.
- To share and manage state at a higher level, making it accessible to multiple child components.
React Controlled Components
- The value prop sets the current value of the input, making it a controlled component.
Props Handling (Advanced)
- React props are just a JavaScript object
- Props Destructuring:
const { search, onSearch } = props const Search = ({ search, onSearch }) => { //component logic } - Nested Destructuring:
const Item = ({
item: {
title,
url,
author,
num_comments,
points,
},
}) => ( <li>
<span>
<a href={url}>{title}</a>
</span>
<span>{author}</span>
<span>{num_comments}</span>
<span>{points}</span>
</li> );
- Spread and Rest Operators:
- The rest operator is used to collect multiple elements and condense them into a single array or object.instead of spreading items out, it gathers them together
- it as a way to copy or expand items in arrays and objects.
React Side-Effects
- you omit the second argument in useEffect,It runs the effect after every render, leading to potential performance issues
React Custom Hooks (Advanced)
- Combines useState and useEffect to create a reliable way to manage persistent state in React.
React Fragments
- A Fragment is a way to group multiple React elements without introducing an additional DOM element.
- Wrap the elements with
<React.Fragment>or its shorthand syntax<>...</>. - Fragments themselves cannot have attributes. Attributes should be applied to the elements within the Fragment.
Reusable React Component
-Make components more generic by using props for customizable behavior and ensuring they are not tightly coupled to specific functionalities.
React Component Composition
- “Children” in React refers to the content placed between the opening and closing tags of a component.
Imperative React
- Unlike useState, useRef doesn’t trigger a re-render when its value changes. It’s often used for mutable values that don’t affect the rendering.
- Use myRef.current to access the current value of a ref created with useRef.
inputRef.current.focus()
Inline Handler in JSX
- avoid using complex logic in JSX
- An inline function in React is often used as a function defined directly within the JSX.
import React , {useState} from 'react';