Part 1 of 5: React Coding Practice Problems

Implementing a simple to-do list with React & building a form with controlled components.

Part 1 of 5: React Coding Practice Problems

- Jon Christie


In this five-part series, I will show. you solutions for some of the most common React coding problems found in interviews today. Let’s start with the following two problems:

  1. Implementing a simple to-do list with React

  2. Building a form with controlled components

Each problem is different and solutions may vary. I will be completing these in JavaScript, but if you would like to see a solution in any other language, contact me!

Implementing a simple to-do list with React

import React, { useState } from 'react';

function TodoList() {
  const [todos, setTodos] = useState([]);
  const [newTodo, setNewTodo] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    setTodos([...todos, newTodo]);
    setNewTodo('');
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input 
          type="text" 
          placeholder="Add a new todo" 
          value={newTodo} 
          onChange={e => setNewTodo(e.target.value)}
        />
        <button type="submit">Add</button>
      </form>
      <ul>
        {todos.map((todo, index) => (
          <li key={index}>{todo}</li>
        ))}
      </ul>
    </div>
  );
}

export default TodoList;

In this example, we are using the useState hook to manage the state of our to-do list. We have two state variables: todos and newTodo. todos is an array that contains all of our to-do items and newTodo is a string that holds the value of the input field where the user can add a new to-do item.

The handleSubmit function is called when the user submits the form and:

  • prevents the default form behavior

  • adds the new todo item to the todos array

  • clears the input field by setting newTodo to an empty string.

In the JSX, we have a form that contains an input field and a submit button. The input field is controlled by the newTodo state variable and the onChange event is used to update the state with the value of the input field. The form's onSubmit event is set to call the handleSubmit function.

Below the form, we have an unordered list that maps over the todos array and displays each todo item as a list item. Each list item is given a unique key so that React can keep track of each item and control its re-renders to improve performance. Check out Why do I need Keys in React Lists? by Adhithi Ravichandran to go into more detail!

This is a basic implementation of a simple to-do list with React. You can easily extend this example to include features such as editing, deleting, and marking todos as complete.

Building a form with controlled components

import React, { useState } from 'react';

function MyForm() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    password: ''
  });

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  }

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input 
          type="text" 
          name="name" 
          value={formData.name} 
          onChange={handleChange}
        />
      </label>
      <br />
      <label>
        Email:
        <input 
          type="email" 
          name="email" 
          value={formData.email} 
          onChange={handleChange}
        />
      </label>
      <br />
      <label>
        Password:
        <input 
          type="password" 
          name="password" 
          value={formData.password} 
          onChange={handleChange}
        />
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;

In this example, we are using the useState hook to manage the state of our form data. We have an object called formData which contains the initial values for the name, email, and password fields. The state variable is set up as an object with properties that match the names of the form fields, so we can use formData.name, formData.email, and formData.password to set the initial values of the form fields.

The handleChange function is called when the user types in any of the input fields. It updates the formData state with the new values using the spread operator, so the previous form data is preserved and only the field that was updated is changed.

The handleSubmit function is called when the user submits the form. It prevents the default form behavior and logs the form data to the console.

In the JSX, we have a form that contains three input fields, each one is labeled, one for name, email, and password. The input field is controlled by the formData state variable and the onChange event is used to update the state with the value of the input field. The form's onSubmit event is set to call the handleSubmit function, which prevents the default and logs the input from the form:

This is a basic example of building a form with controlled components in React. You can easily extend this example to include features such as form validation, submitting the form data to a server, and handling errors.

WORKING CODE


- Jon Christie

jonchristie.net