search
HomeWeb Front-endJS TutorialUnderstanding React in ins

Understanding React in ins

Dec 03, 2024 am 04:34 AM

Understanding React in ins

Looking for a quick way to grasp the basics of React? Feeling overwhelmed by lengthy tutorials? In just 5 minutes, you'll learn enough to read and understand most React code.

Table of Contents

  • What is React?
  • Core Concepts
  • Common Patterns
  • Putting It All Together
  • That's It!

What is React?

React is a JavaScript library for building UIs like buttons or forms.

Think of building with LEGO blocks. Instead of creating one big castle, you build using smaller, reusable pieces that connect together. React lets you build web interfaces using reusable pieces called "components".

Here's what React code looks like:

// A simple React component
function Greeting() {
  return <h1 id="Hello">Hello!</h1>;
}

This special syntax is called JSX - it lets you write HTML-like code in JavaScript.

React helps you:

  • Break down complex UIs into manageable pieces
  • Handle UI and data efficiently using a Virtual DOM system
  • Update webpages automatically whenever your data changes

Core Concepts

1. Components ?

Components are like LEGO blocks in React. They are reusable UI pieces you can combine.

// A simple component
function Welcome({ name }) {
  return <h1 id="Hello-name">Hello, {name}!</h1>;
}

// Using it
<welcome name="Alice"></welcome>

2. Props ?

Props are data passed to components - like function parameters.

// 'name' and 'age' are passed to UserCard() as props
function UserCard({ name, age }) {
  return (
    <div>
      <h2 id="name">{name}</h2>
      <p>Age: {age}</p>
    </div>
  );
}

<usercard name="Alice" age="{25}"></usercard>

Note: Props are read-only.

3. State ?

State is data that can change. When it changes, React updates the UI automatically.

function LikeButton() {
  // 'likes' is state
  // 'setLikes' is function to update the state
  const [likes, setLikes] = useState(0);

  return (
    <button onclick="{()"> setLikes(likes + 1)}>
      Likes: {likes}
    </button>
  );
}

Note: useState(0) sets up state with an initial value of 0 (more about Hooks below).

4. Hooks ?

Hooks are functions that let components use React features. They always start with "use".

  • useState: for managing changing data (state)

    const [count, setCount] = useState(0); // Initialize count with 0
    
  • useEffect: for running code at specific times (like API calls)

    useEffect(() => {
        fetchData(); // Get data
    }, []);          // Run once when page loads
    

Common Patterns

Conditional Rendering

Show different content based on conditions:

function Greeting({ isLoggedIn }) {
  return isLoggedIn
   ? <h1 id="Welcome">Welcome!</h1>
   : <h1 id="Please-log-in">Please log in</h1>;
}

When isLoggedIn is true, shows "Welcome!", otherwise shows "Please log in".

Usage:

<greeting isloggedin="{true}"></greeting>   // "Welcome!"
<greeting isloggedin="{false}"></greeting>  // "Please log in"

Event Handling

Handle user interactions like clicks:

function ToggleButton() {
 // Track button state (ON/OFF)
  const [isOn, setIsOn] = useState(false);

  return (
    <button onclick="{()"> setIsOn(!isOn)}>
      {isOn ? 'ON' : 'OFF'}
    </button>
  );
}

When clicked, the button text switches between "ON" and "OFF".

Usage:

<togglebutton></togglebutton>  // Shows: "OFF" by default

Putting It All Together ?

Here's a real example using what we learned:

function LikeButton({ initialLikes = 0 }) {
  const [likes, setLikes] = useState(initialLikes);

  return (
    <button onclick="{()"> setLikes(likes + 1)}>
      {likes === 0 ? '♡' : '?'} {likes > 0 && likes}
    </button>
  );
}

This LikeButton component:

  • Gets initial likes count as props
  • Shows empty heart (♡) when count is 0
  • Shows pink heart (?) with number when likes > 0
  • Updates heart and count when clicked

Usage Example:

// A simple React component
function Greeting() {
  return <h1 id="Hello">Hello!</h1>;
}

That's It! ?

You now know the React basics! While there's more to learn, you can understand most React code you see.

Ready to Start?

There are several ways to create a React project:

  • Next.js: Full-stack React framework, recommended for most new projects
  • Gatsby: React framework for fast CMS-backed websites
  • Vite: Modern and fast build tool, great for learning React and building single-page applications

Details are here.

Happy coding✨

The above is the detailed content of Understanding React in ins. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.