When building interactive web applications with React, forms are a cornerstone for user input. "Controlled forms" refer to the practice of letting React manage the state of your form inputs. Instead of the browser owning the input's value, you bind the input's value attribute to a piece of your component's state. Any time the user types, an onChange event handler fires, which then updates this state. This pattern establishes a "single source of truth" for the form data within your React component, making it predictable, easier to validate, and simpler to reset or pre-fill. It gives you immediate control over the input's behavior and value, reacting seamlessly to user interactions.
Rendering dynamic collections of data, like a list of products or user comments, is handled elegantly in React using JavaScript's map() method on an array. Each item in your data array is transformed into a React element. A critical aspect here is providing a unique key prop for each list item. This key helps React efficiently identify which items have changed, been added, or removed during updates, optimizing performance and preventing unexpected behavior, especially with complex lists.
"Conditional rendering," meanwhile, is about displaying different UI elements or components based on certain conditions (e.g., if a user is logged in, if data is loading, or if a list is empty). You can achieve this using standard JavaScript if/else statements, ternary operators (condition ? <ComponentA /> : <ComponentB />), or logical && (condition && <Component />) directly within your JSX. These techniques allow you to create dynamic user interfaces that respond intelligently to your application's state, showing a loading spinner while fetching data, an error message if something went wrong, or a "no items found" message for an empty list, thus making your application reactive and user-friendly.
Key Takeaways
- Controlled forms bind input values to component state for predictable data management.
- Use
array.map()to render lists, always including a uniquekeyprop for each item. - Conditional rendering (
if/else, ternary,&&) dynamically shows/hides UI based on state. - These patterns are fundamental for building interactive, data-driven React applications.
Code Example
How this code works
This code creates a simple interactive input field that welcomes a user by name. It allows a user to type their name, and immediately displays a personalized greeting. When the input field is empty, it prompts the user to enter their name. This demonstrates how React manages form inputs (making them "controlled components") and conditionally renders different content based on user input.
The useState('') hook initializes a piece of state called name, starting as an empty string. The handleChange function is triggered every time a user types into the input box. It takes the current value from the input field (event.target.value) and updates the name state, which in turn causes the component to re-render. The input element is "controlled" because its value={name} is always dictated by the name state, and onChange={handleChange} ensures the state is updated whenever the input changes.
Crucially, the line {name ? <p>Hello, {name}!</p> : <p>Please enter your name above.</p>} uses a conditional check. Initially, name is an empty string, which JavaScript treats as a "falsy" value. This subtle detail means the prompt "Please enter your name above." is displayed by default. As soon as a user types anything, name becomes a "truthy" value, and the personalized "Hello, [name]!" greeting instantly appears instead.