Author: saqibkhan

  • Tabs Component

    This example shows how to create a simple tabbed interface.

    jsxCopy codeimport React, { useState } from 'react';
    import ReactDOM from 'react-dom';
    
    function Tabs() {
      const [activeTab, setActiveTab] = useState('Tab1');
    
      const renderContent = () => {
    
    switch (activeTab) {
      case 'Tab1':
        return <div>This is content for Tab 1.</div>;
      case 'Tab2':
        return <div>This is content for Tab 2.</div>;
      case 'Tab3':
        return <div>This is content for Tab 3.</div>;
      default:
        return null;
    }
    }; return (
    <div>
      <h1>Tabs Example</h1>
      <div>
        <button onClick={() => setActiveTab('Tab1')}>Tab 1</button>
        <button onClick={() => setActiveTab('Tab2')}>Tab 2</button>
        <button onClick={() => setActiveTab('Tab3')}>Tab 3</button>
      </div>
      <div>{renderContent()}</div>
    </div>
    ); } ReactDOM.render(<Tabs />, document.getElementById('root'));
  • Simple Shopping Cart

    This example demonstrates how to build a basic shopping cart with the ability to add and remove items.

    jsxCopy codeimport React, { useState } from 'react';
    import ReactDOM from 'react-dom';
    
    const items = [
      { id: 1, name: 'Apple', price: 1 },
      { id: 2, name: 'Banana', price: 0.5 },
      { id: 3, name: 'Orange', price: 0.8 },
    ];
    
    function ShoppingCart() {
      const [cart, setCart] = useState([]);
    
      const addItem = (item) => {
    
    setCart(&#91;...cart, item]);
    }; const removeItem = (id) => {
    setCart(cart.filter(item =&gt; item.id !== id));
    }; const total = cart.reduce((acc, item) => acc + item.price, 0); return (
    &lt;div&gt;
      &lt;h1&gt;Shopping Cart&lt;/h1&gt;
      &lt;h2&gt;Items:&lt;/h2&gt;
      &lt;ul&gt;
        {items.map(item =&gt; (
          &lt;li key={item.id}&gt;
            {item.name} - ${item.price}
            &lt;button onClick={() =&gt; addItem(item)}&gt;Add to Cart&lt;/button&gt;
          &lt;/li&gt;
        ))}
      &lt;/ul&gt;
      &lt;h2&gt;Cart:&lt;/h2&gt;
      &lt;ul&gt;
        {cart.map(item =&gt; (
          &lt;li key={item.id}&gt;
            {item.name} - ${item.price}
            &lt;button onClick={() =&gt; removeItem(item.id)}&gt;Remove&lt;/button&gt;
          &lt;/li&gt;
        ))}
      &lt;/ul&gt;
      &lt;h3&gt;Total: ${total.toFixed(2)}&lt;/h3&gt;
    &lt;/div&gt;
    ); } ReactDOM.render(<ShoppingCart />, document.getElementById('root'));
  • Parent-Child Component Communication

    This example demonstrates communication between parent and child components.

    jsxCopy codeimport React, { useState } from 'react';
    import ReactDOM from 'react-dom';
    
    function ParentComponent() {
      const [message, setMessage] = useState('Hello from Parent!');
    
      return (
    
    &lt;div&gt;
      &lt;h1&gt;Parent Component&lt;/h1&gt;
      &lt;ChildComponent message={message} /&gt;
      &lt;button onClick={() =&gt; setMessage('Message Updated!')}&gt;Update Message&lt;/button&gt;
    &lt;/div&gt;
    ); } function ChildComponent({ message }) { return <h2>Child Component: {message}</h2>; } ReactDOM.render(<ParentComponent />, document.getElementById('root'));
  • Basic Counter with Hooks

    A simple counter application using hooks.

    jsxCopy codeimport React, { useState } from 'react';
    import ReactDOM from 'react-dom';
    
    function Counter() {
      const [count, setCount] = useState(0);
    
      return (
    
    &lt;div&gt;
      &lt;h1&gt;Count: {count}&lt;/h1&gt;
      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;
      &lt;button onClick={() =&gt; setCount(count - 1)}&gt;Decrement&lt;/button&gt;
      &lt;button onClick={() =&gt; setCount(0)}&gt;Reset&lt;/button&gt;
    &lt;/div&gt;
    ); } ReactDOM.render(<Counter />, document.getElementById('root'));
  • Form Handling Example

    This example demonstrates form handling with controlled components.

    jsxCopy codeimport React, { useState } from 'react';
    import ReactDOM from 'react-dom';
    
    function FormExample() {
      const [formData, setFormData] = useState({ name: '', email: '' });
    
      const handleChange = (e) => {
    
    const { name, value } = e.target;
    setFormData({ ...formData, &#91;name]: value });
    }; const handleSubmit = (e) => {
    e.preventDefault();
    alert(Name: ${formData.name}, Email: ${formData.email});
    }; return (
    &lt;form onSubmit={handleSubmit}&gt;
      &lt;h1&gt;Contact Form&lt;/h1&gt;
      &lt;input
        type="text"
        name="name"
        placeholder="Name"
        value={formData.name}
        onChange={handleChange}
      /&gt;
      &lt;input
        type="email"
        name="email"
        placeholder="Email"
        value={formData.email}
        onChange={handleChange}
      /&gt;
      &lt;button type="submit"&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
    ); } ReactDOM.render(<FormExample />, document.getElementById('root'));
  • Fetch Data from an API

    This example fetches data from a public API and displays it.

    jsxCopy codeimport React, { useEffect, useState } from 'react';
    import ReactDOM from 'react-dom';
    
    function UserList() {
      const [users, setUsers] = useState([]);
      const [loading, setLoading] = useState(true);
    
      useEffect(() => {
    
    const fetchUsers = async () =&gt; {
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      const data = await response.json();
      setUsers(data);
      setLoading(false);
    };
    fetchUsers();
    }, []); if (loading) return <div>Loading...</div>; return (
    &lt;div&gt;
      &lt;h1&gt;User List&lt;/h1&gt;
      &lt;ul&gt;
        {users.map(user =&gt; (
          &lt;li key={user.id}&gt;{user.name} - {user.email}&lt;/li&gt;
        ))}
      &lt;/ul&gt;
    &lt;/div&gt;
    ); } ReactDOM.render(<UserList />, document.getElementById('root'));
  • Simple Todo List

    This example demonstrates managing a list of tasks using state.

    jsxCopy codeimport React, { useState } from 'react';
    import ReactDOM from 'react-dom';
    
    function TodoApp() {
      const [tasks, setTasks] = useState([]);
      const [inputValue, setInputValue] = useState('');
    
      const addTask = () => {
    
    if (inputValue) {
      setTasks(&#91;...tasks, inputValue]);
      setInputValue('');
    }
    }; const removeTask = (index) => {
    const newTasks = tasks.filter((_, i) =&gt; i !== index);
    setTasks(newTasks);
    }; return (
    &lt;div&gt;
      &lt;h1&gt;Todo List&lt;/h1&gt;
      &lt;input
        type="text"
        value={inputValue}
        onChange={(e) =&gt; setInputValue(e.target.value)}
        placeholder="Add a new task"
      /&gt;
      &lt;button onClick={addTask}&gt;Add&lt;/button&gt;
      &lt;ul&gt;
        {tasks.map((task, index) =&gt; (
          &lt;li key={index}&gt;
            {task} &lt;button onClick={() =&gt; removeTask(index)}&gt;Remove&lt;/button&gt;
          &lt;/li&gt;
        ))}
      &lt;/ul&gt;
    &lt;/div&gt;
    ); } ReactDOM.render(<TodoApp />, document.getElementById('root'));
  • Popular in Enterprise Applications

    Many large-scale applications from companies like Facebook, Instagram, Airbnb, and Netflix use React due to its scalability, performance, and flexibility. This widespread adoption is a testament to its reliability and effectiveness for building complex UIs.

  • Performance Optimization

    React provides tools like shouldComponentUpdate and React.memo to prevent unnecessary re-renders. These optimizations help improve the performance of applications, especially in complex UIs with many components.

  • Functional Components vs. Class Components

    While React supports both class and functional components, functional components have become the standard due to their simplicity and the ability to use hooks. This trend has led to a cleaner codebase and a more modern development approach.