logo

React Components

Learn how to create and use React components

React Components

Components are the building blocks of React applications. They let you split the UI into independent, reusable pieces.

Function Components

// Simple function component
function Welcome(props) {
  return <h1>Hello, {props.name}!</h1>;
}

// Arrow function component
const Greeting = (props) => {
  return <div>Welcome, {props.user}!</div>;
};

// Component with destructured props
const UserCard = ({ name, email, avatar }) => {
  return (
    <div className="user-card">
      <img src={avatar} alt={name} />
      <h3>{name}</h3>
      <p>{email}</p>
    </div>
  );
};

JSX Syntax

// JSX elements
const element = <h1>Hello World</h1>;

// JSX with expressions
const name = "Alice";
const greeting = <h1>Hello, {name}!</h1>;

// JSX with attributes
const image = <img src="photo.jpg" alt="Profile" className="avatar" />;

// JSX with children
const container = (
  <div className="container">
    <h1>Title</h1>
    <p>This is a paragraph.</p>
  </div>
);

// Conditional rendering
const status = isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>;

// List rendering
const items = ['apple', 'banana', 'orange'];
const listItems = (
  <ul>
    {items.map((item, index) => (
      <li key={index}>{item}</li>
    ))}
  </ul>
);

Props

// Parent component passing props
function App() {
  const user = {
    name: "John Doe",
    age: 30,
    email: "john@example.com"
  };

  return (
    <div>
      <UserProfile user={user} isActive={true} />
      <Button text="Click me" onClick={handleClick} />
    </div>
  );
}

// Child component receiving props
function UserProfile({ user, isActive }) {
  return (
    <div className={`profile ${isActive ? 'active' : 'inactive'}`}>
      <h2>{user.name}</h2>
      <p>Age: {user.age}</p>
      <p>Email: {user.email}</p>
    </div>
  );
}

// Props with default values
function Button({ text = "Click", onClick, disabled = false }) {
  return (
    <button onClick={onClick} disabled={disabled}>
      {text}
    </button>
  );
}

// Props validation with PropTypes
import PropTypes from 'prop-types';

UserProfile.propTypes = {
  user: PropTypes.shape({
    name: PropTypes.string.isRequired,
    age: PropTypes.number,
    email: PropTypes.string
  }).isRequired,
  isActive: PropTypes.bool
};

Component Composition

// Container component
function Card({ children, title }) {
  return (
    <div className="card">
      {title && <h3 className="card-title">{title}</h3>}
      <div className="card-content">
        {children}
      </div>
    </div>
  );
}

// Using composition
function ProfileCard() {
  return (
    <Card title="User Profile">
      <img src="avatar.jpg" alt="User" />
      <h4>John Doe</h4>
      <p>Software Developer</p>
      <button>Follow</button>
    </Card>
  );
}

// Higher-Order Component pattern
function withLoading(WrappedComponent) {
  return function WithLoadingComponent({ isLoading, ...props }) {
    if (isLoading) {
      return <div>Loading...</div>;
    }
    return <WrappedComponent {...props} />;
  };
}

const UserListWithLoading = withLoading(UserList);

Event Handling

function InteractiveButton() {
  const handleClick = (event) => {
    event.preventDefault();
    console.log('Button clicked!');
  };

  const handleMouseEnter = () => {
    console.log('Mouse entered!');
  };

  return (
    <button 
      onClick={handleClick}
      onMouseEnter={handleMouseEnter}
      className="interactive-btn"
    >
      Click me!
    </button>
  );
}

// Form handling
function ContactForm() {
  const handleSubmit = (event) => {
    event.preventDefault();
    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData);
    console.log('Form data:', data);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="name" placeholder="Your name" required />
      <input name="email" type="email" placeholder="Your email" required />
      <textarea name="message" placeholder="Your message"></textarea>
      <button type="submit">Send</button>
    </form>
  );
}

Conditional Rendering

function UserDashboard({ user, isLoggedIn }) {
  // Early return
  if (!isLoggedIn) {
    return <LoginForm />;
  }

  return (
    <div>
      <h1>Dashboard</h1>
      
      {/* Conditional with && */}
      {user.isAdmin && <AdminPanel />}
      
      {/* Conditional with ternary */}
      {user.notifications.length > 0 ? (
        <NotificationList notifications={user.notifications} />
      ) : (
        <p>No new notifications</p>
      )}
      
      {/* Multiple conditions */}
      {user.isPremium ? (
        <PremiumFeatures />
      ) : user.isTrialUser ? (
        <TrialFeatures />
      ) : (
        <BasicFeatures />
      )}
    </div>
  );
}

Components are the heart of React - master them to build powerful, reusable UIs!