Understanding React

Understanding React
0

#1

So, I am going through my udemy course on React, and unfortunately the react section instructor is not as good as the previous instructor as far as explaining. He pretty much just jumps around the code trying to explain. In this example it is just adding new to dos on a to do list.

Heres his full code

import React, { Component } from 'react';
import './App.css';

const TodoItem = ({text}) => (
  <li>{text}</li>
);

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      todos: [],
      newTodo: ''
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(e) {
    e.preventDefault();
    const todos = [...this.state.todos, this.state.newTodo];
    this.setState({todos, newTodo: ''});
  }
  render() {
    const {newTodo} = this.state;
    const todos = this.state.todos.map((t, i) => (
      <TodoItem key={i} text={t} />
    ));
    return (
      <div className="App">
        <h1>Simple Todo App</h1>
        <form onSubmit={this.handleSubmit}>
          <input
            className="todo-input"
            autoComplete="off"
            type="text"
            name="newTodo"
            placeholder="What needs to be done?"
            value={newTodo}
            onChange={(e) => this.setState({[e.target.name]: e.target.value })}
          />
          <button
            type="submit"
            className="save-button"
          >
            SAVE
          </button>
        </form>
        <div className="todo-content">
          <ol>
            {todos}
          </ol>
        </div>
      </div>
    );
  }
}

export default App;

First there is this code at the very top

const TodoItem = ({text}) => (
  <li>{text}</li>
);

So I know this a destructed function. im assuming hes using this to make it more organized? Because thats being used to map the array, and usually I though mapping an array would look like. Second question on that would be the key. it was said the index would fit as the key as long as the index of the array never changed. But in the full code we are adding new li’s so the index would change?

 const text = this.state.todo.map((todo, index) => (
      <li key={index}>{todo}</li> 

Then this. So todos is a empty array as state, and on the handleSubmit todos is still an empty array with this.state.todos. and set state is updating the todos ?

handleSubmit(e) {
    e.preventDefault();
    const todos = [...this.state.todos, this.state.newTodo];
    this.setState({todos, newTodo: ''});
  }
  render() {
    const {newTodo} = this.state;
    const todos = this.state.todos.map((t, i) => (
      <TodoItem key={i} text={t} />
    ));

#2

It’s hard to understand your specific question. You seem like you are answering your own questions a lot. Also there seems to be a lot of questions here. Please be more specific and ask your questions one at a time. Otherwise you are unlikely to receive a response. To explain this entire code in a forum post would take several pages of typing.


#3

I figured it was not the best phrased question since it’s been a while without a response. If it looks like I’m answering my own questions they are more of guesses, and I’m not sure If I’m right. I think the biggest thing now is what updates the todos array? setState is setting the todos, and clearing the input. I guess I don’t see exactly where todos gets the values for the new todos once the button is pressed? The course instructor is not very clear and jumps around a lot


#4

React takes the state and renders out HTML, that’s the point of React. So the new todos are being added to the state with setState.


#5

What’s the name of this course? i recently purchased a React course on udemy which I plan to start soon and I’d like to know if you are talking of the same course here.


#6

It is the advanced web development course by colt Steele, Ellie, and I can’t recal the other two instructors. I loved colts first web development course, so I picked this one up as well


#7

Ok. Here is where im confused though…what is telling react to add the new todo to the array? Like in javascript I could use .push, and know thats what is adding the value to the array. When the button is pushed who is adding that value entered into the array? what is the todos array getting its value from?


#8

App component has handleSubmit(). This modifies the todos state by combining previous todos and newTodo. Then, setState() is called to update todos with the modified state. Hence, whenever handleSubmit() is called todos state gets whatever was in the newTodo.

State change re-renders the App component, and App gets the updated todos. This state change detection and re-rendering is handled by React.


#9

Ok. In his run of the code the text input was cleared every time the submit button was pushed. So inside input he has value set to newTodo. And value is set as an empty ‘ ‘ in the state. So I though that was just for clearing the input?


#10

Well obviously whenever user type something to input, onChange event is triggered and saves the input in newTodo. Regardless to this, whenever a user submits,

const todos = [...this.state.todos, this.state.newTodo]

This line adds newTodo to todos.

Registering and dispatching events and component refreshes are handled by React.


#11

Gotcha! So how exactly does input know to save it to the new todo variable? Because of the value being newTodo in the input?


#12
onChange={(e) => this.setState({[e.target.name]: e.target.value })

You can see that whenever change happens the e.target.name = 'newTodo' state is set to e.target.value.


#13

Ok! See he never explained what e.target is or what it even does. Nor does he explain the line you pointed out that adds the newTodo to todos. Makes more sense!!!


#14

Perhaps, the instructor assumed you already have a sufficient JavaScript knowledge since registering event in React is almost identical to Native JS. e is the event parameter that you receive.


#15

I haven’t done the course so I can only go off what you’re getting from it here, but it seems very much that it expects a base level of JS knowledge. event.target, for example: that isn’t React-specific, it is just the property on the standard event object that specifies the target element for that particular event.

I assume that is the reason he’s going through things quite quickly here. It’s not a massive issue - ask away in this thread, and you should get good specific answers - but be prepared for it being a bit of a slog!

Edit: and the two fields (the string for the new todo, and then a list of todos), thats a really common pattern. What it means is that the <input> is linked directly to the newTodo, and as the user types, the state of that field is kept in sync. Then when you hit submit, you don’t need that anymore, so it gets cleared down to an empty string and the value moved to the list of todos. The newTodo is transient, all it is is a way to keep hold of the value a user types in until they decide to save that value. The array of todos is the real state of the whole application