YouTip LogoYouTip

React Components

React Components \n\nReact components are the basic units for building React applications. You can think of a component as a reusable, independent UI unit, where each component encapsulates its own structure, style, logic, and state.\n\nReact components are the building blocks of an application. A component can be as small as a button, or as large as an entire page.\n\n!(#)\n\nComponents can be divided into: **Function Components** and **Class Components**.\n\nFrom a technical perspective, a React component is simply a JavaScript function or class that returns a React element (usually JSX).\n\n// The simplest component function Hello() { return

Hello, World!

;}\n\nBreak down a complex UI into a component tree:\n\nAppβ”œβ”€β”€ Headerβ”‚ β”œβ”€β”€ Logoβ”‚ └── Navigationβ”‚ β”œβ”€β”€ NavItemβ”‚ └── NavItemβ”œβ”€β”€ Mainβ”‚ β”œβ”€β”€ Sidebarβ”‚ └── Contentβ”‚ β”œβ”€β”€ Articleβ”‚ └── Article└── Footer\n\n* * *\n\n## Function Components\n\nFunction components are a concise way to define components.\n\nA function component is a JavaScript function that accepts props and returns a React element.\n\nBasic syntax:\n\n// Method 1: Function declaration function Welcome(props) { return

Hello, {props.name}

;}// Method 2: Arrow function const Welcome = (props) => { return

Hello, {props.name}

;};// Method 3: Simplified notation (single-line return) const Welcome = (props) =>

Hello, {props.name}

;\n\nCreate a simple function component:\n\n## src/Welcome.js file:\n\nimport React from 'react';\n\n// Define a function component\n\nfunction Welcome(props){\n\nreturn

Hello,{props.name}!

;\n\n}\n\nexport default Welcome;\n\nRender this component in src/index.js:\n\n## src/index.js file:\n\nimport React from 'react';\n\nimport ReactDOM from 'react-dom';\n\nimport'./index.css';\n\nimport Welcome from './Welcome';\n\nconst root = ReactDOM.createRoot(document.getElementById("root"));\n\n// Render the Welcome component and pass the name attribute\n\n root.render();\n\nThis example shows a simple component that accepts a name attribute and displays "Hello, World!" on the page.\n\n* * *\n\n## Class Components\n\nClass components are defined using ES6 class syntax, typically used when there is a need to manage state or use lifecycle methods.\n\nBasic syntax:\n\nimport React, { Component } from 'react';class Welcome extends Component { render() { return

Hello, {this.props.name}

; }}\n\nCreate a class component:\n\n## Example\n\nimport React,{ Component } from 'react';\n\nclass Welcome extends Component {\n\n render(){\n\nreturn

Hello,{this.props.name}!

;\n\n}\n\n}\n\nexport default Welcome;\n\nRender this component in src/index.js:\n\n## Example\n\nimport React from 'react';\n\nimport ReactDOM from 'react-dom';\n\nimport'./index.css';\n\nimport Welcome from './Welcome';\n\nconst root = ReactDOM.createRoot(document.getElementById("root"));\n\n// Render the Welcome component and pass the name attribute\n\n root.render();\n\n* * *\n\n## Test Example\n\nNext, we will encapsulate a component that outputs "Hello World!", and the component name is HelloMessage:\n\n## React Example\n\nfunction HelloMessage(props){return

Hello World!

; }const element = ; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(element);\n\n[Try it out Β»](#)\n\n### Example Analysis:\n\n1. We can use a function to define a component:\n\nfunction HelloMessage(props) { return

Hello World!

;}\n\nYou can also use an ES6 class to define a component:\n\nclass Welcome extends React.Component { render() { return

Hello World!

; }}\n\n2. **const element = ** is a user-defined component.\n\n> Note that native HTML element names start with a lowercase letter, while custom React class names start with an uppercase letter. For example, HelloMessage cannot be written as helloMessage. In addition, note that a component class can only contain one top-level tag, otherwise it will throw an error.\n\nIf we need to pass parameters to a component, we can use the **this.props** object, as shown in the following example:\n\n## React Example\n\nfunction HelloMessage(props){return

Hello{props.name}!

; }const element = ; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(element);\n\n[Try it out Β»](#)\n\nIn the above example, the **name** attribute is retrieved via props.name.\n\n> Note that when adding attributes, the class attribute needs to be written as className, and the for attribute needs to be written as htmlFor. This is because class and for are JavaScript reserved words.\n\n* * *\n\n## Composite Components\n\nWe can create multiple components to synthesize a component, that is, to separate the different functional points of a component.\n\nIn the following example, we implement a component that outputs the website name and URL:\n\n## React Example\n\nfunction Name(props){return

Website name:{props.name}

; }function Url(props){return

{props.url}

; }function Nickname(props){return

Website nickname:{props.nickname}

; }function App(){return(
); }const root = ReactDOM.createRoot(document.getElementById("root")); root.render();\n\n[Try it out Β»](#)\n\nIn the example, the App component uses the Name, Url, and Nickname components to output the corresponding information.\n\n* * *\n\n## Props (Properties)\n\nProps are the way to pass data between components, similar to function parameters.\n\n### Basic Usage\n\n// Parent component passes props to function App() { return (
);}// Child component receives props function Greeting(props) { return (

Hello, {props.name}!

Age: {props.age}

);}\n\n### Props Destructuring\n\n// Recommended: Direct destructuring for function Greeting({ name, age }) { return (

Hello, {name}!

Age: {age}

);}// Destructuring with default values for function Button({ text = "Submit", variant = "primary", disabled = false }) { return ( );}\n\n### Types of Props\n\nProps can be any JavaScript value:\n\nfunction Demo() { const user = { name: "Alice", age: 25 }; const numbers = [1, 2, 3, 4, 5]; const handleClick = () => alert("Clicked!"); return ( <MyComponent // String title="Hello" // Number count={42} // Boolean value isActive={true} // Array items={numbers} // Object user={user} // Function onClick={handleClick} // JSX children={

This is content

} /> );}\n\n### Children Props\n\nSpecial props used to pass child content to a component:\n\n// Method 1: Using props.childrenfunction Card(props) { return (
{props.children}
);}// Method 2: Destructuring children for function Card({ children, title }) { return (
{title &&

{title}

}
{children}
);}// Using function App() { return (

This is the card content

);}\n\n### Immutability of Props\n\n**Important Principle**: Never modify props!\n\n// Error: Modifying props for function BadComponent(props) { props.name = "Changed"; // Absolutely do not do this! return

{props.name}

;}// Correct: Treat props as read-only for function GoodComponent({ name }) { const displayName = name.toUpperCase(); // Create a new value return

{displayName}

;}\n\n* * *\n\n## Component Composition and Reuse\n\n### Composition Pattern\n\n// Basic component function Avatar({ src, alt }) { return {alt};}function UserInfo({ name, email }) { return (

{name}

{email}

);}// Combine into a complex component function UserCard({ user }) { return (
<Avatar src={user.avatar} alt={
← React StateC Arrays β†’