React Beginner 4: Props, State & Events

In this tutorial, you will learn how to make React components dynamic and interactive using props, state, and event handling.

Introduction

Components are the building blocks of React, but without props and state, they are static. Props allow you to pass data between components, state allows components to manage their own data, and events allow users to interact with your UI.

1. Using Props

Props are short for “properties.” They are read-only values passed from a parent component to a child component.

Example:

function Greeting(props) {
  return <h2>Hello, {props.name}!</h2>;
}

function App() {
  return (
    <div>
      <Greeting name="Alice" />
      <Greeting name="Bob" />
    </div>
  );
}

export default App;

In this example, the Greeting component receives different names from the parent component.

2. Using State

State allows a component to manage data that can change over time. You use the useState hook in functional components.

Example:

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default Counter;

Clicking the button updates the state and re-renders the component.

3. Handling Events

React uses camelCase for event handlers, like onClick, onChange, etc.

Example:

function TextInput() {
  const [text, setText] = useState('');

  return (
    <div>
      <input 
        type="text" 
        value={text} 
        onChange={e => setText(e.target.value)} 
        placeholder="Type something" 
      />
      <p>You typed: {text}</p>
    </div>
  );
}

export default TextInput;

This input field updates the state as you type and displays the current value.

4. Summary

In this tutorial, you learned:

  • How to pass data to components using props
  • How to manage component data using state
  • How to handle user events to make components interactive

Next, in React Beginner 5, you will build a small real-world app (like a Todo list) using everything learned so far.

Previous Article

React Beginner 3: Understanding Components & JSX

Next Article

React Beginner 5: Building Your First Todo App

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨