lundi 27 juillet 2020

have return statement and return nothing

i'm beginner on react(javascript), doing todo app, have a questions related to having a return inside if statement but returning nothing(if user writes nothing and press enter it does not count it), but when i take it away it will affect the behaviour of todo app. My question is what is the meaning of this part of the code if (!value) { return }
if there is no value it will return what ? and why taking away the 'return' it will change the behaviour of todo app ? here is code:

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

function Todo({ tod, index }) {
  return <div className="todo">{tod.text}</div>
}
function TodoForm({ addTodo }) {
  const [value, setValue] = useState('');
  console.log(value)

  const handleSubmit = e => {
    e.preventDefault();
    if (!value) {
      return
    }
    addTodo(value);
    setValue('');

  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        className="input"
        value={value}
        placeholder="Add Todo..."
        onChange={e => setValue(e.target.value)}

      />

    </form>
  )
}

function App() {
  const [todos, setTodos] = useState([
    {
      text: ' Learn by doing',
      isCompleted: false
    }
  ]);

  const addTodo = text => {
    const newTodos = [...todos, { text }];
    setTodos(newTodos);
  }

  return (
    <div className="app">
      <div className="todo-List">
        {todos.map((todo, index) =>
          <Todo key={index} index={index} tod={todo} />
        )}
        <TodoForm addTodo={addTodo} />
      </div>
    </div>
  )

}
export default App;

here i have javascript code where i'm trying to have same kind of statement as the code above ( if(!text){ return } ) here it does not matter if i have 'return' or dont have, it is the same both ways(why in previous example it was different ?) :

function myFunction(text) {
var text=document.getElementById('text').value

event.preventDefault();
console.log(text);

if(!text){
return 
}
else{
document.getElementById('demo').innerHTML = "Text typed: "+text; // if nothing
}}
<form onsubmit="myFunction()">
<input  type="text" id="text" >
</form>

<p id="demo"></p>

English is not my mother language so sorry for mistakes.

Aucun commentaire:

Enregistrer un commentaire