16

React - useRef hook

 5 years ago
source link: https://www.tuicool.com/articles/hit/7FJJZzr
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

If you already read my previouspost we talk about how to create a simple todo with useState and useReducer . Today we’ll see how we can use useRef to refer to our element.

UseRefreturns a mutable ref object whose .current property is initialised to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

const refContainer = useRef(initialValue);

To clarify better how we can use useRef we take the previous example and we’ll apply the required changes. React few days ago release a new version 16.8.0-alpha.0 and if you want to use hooks you need to change your package.json:

react": "16.8.0-alpha.0",
"react-dom": "16.8.0-alpha.0",

In the previouspost the result was:

import React, { useState, useReducer } from "react";


const todoListReducer = (
  state: string[],
  action: { type: string; value: string }
) => {
  switch (action.type) {
    case "ADD":
      return […state, action.value];
    case "REMOVE":
      return state.filter((todo: string) => todo !== action.value);
    default:
      return state;
  }
};


const Todo = () => {
  const [todoList, dispatch] = useReducer(todoListReducer, []);
  const [todoName, setTodoName] = useState("");
 
  const inputChangeHandler = (evt: React.ChangeEvent<HTMLInputElement>) => {
    setTodoName(evt.target.value);
  };
  const todoAddHandler = () => {
    dispatch({ type: "ADD", value: todoName });
  };
  const todoRemoveHandler = (todoItem: string) => {
    dispatch({ type: "REMOVE", value: todoItem });
  };
  return (
    <React.Fragment>
      <input
        type="text"
        placeholder="Todo"
        onChange={inputChangeHandler}
        value={todoName}
      />
      <button type="submit" onClick={todoAddHandler}>
        Add
      </button>
      <ul>
        {todoList.map((todo: string) => (
          <ul key={todo} onClick={() => todoRemoveHandler(todo)}>
            {todo}
          </ul>
        ))}
      </ul>
    </React.Fragment>
  );
};


export default Todo;

view raw todo_final.tsx hosted with ❤ by GitHub

We honestly don’t need to perform too many changes but let’s do it togheter:

  • The first thing we need to do is to declare our useRef element:
const todoInputRef = useRef
<any>
 ("");
</any>
  • Now we need to use todoInputRef and for that we’ll change our input:
input type="text" placeholder="Todo" ref={todoInputRef}

As you can see we removed the value and the onChange handler.

  • In our todoAddHandler we’ll extract the value using our todoInputRef:
const todoAddHandler = () => {    
const todoName = todoInputRef.current.value;    
dispatch({ type: "ADD", value: todoName });  };

This is the full code:

import React, { useState, useReducer, useRef } from "react";


const todoListReducer = (
  state: string[],
  action: { type: string; value: string }
) => {
  switch (action.type) {
    case "ADD":
      return […state, action.value];
    case "REMOVE":
      return state.filter((todo: string) => todo !== action.value);
    default:
      return state;
  }
};


const TodoRef = () => {
  const [todoList, dispatch] = useReducer(todoListReducer, []);
  const todoInputRef = useRef<any>("");


  const todoAddHandler = () => {
    const todoName = todoInputRef.current.value;
    dispatch({ type: "ADD", value: todoName });
  };
  const todoRemoveHandler = (todoItem: string) => {
    dispatch({ type: "REMOVE", value: todoItem });
  };
  return (
    <React.Fragment>
      <input type="text" placeholder="Todo" ref={todoInputRef} />
      <button type="submit" onClick={todoAddHandler}>
        Add
      </button>
      <ul>
        {todoList.map((todo: string) => (
          <ul key={todo} onClick={() => todoRemoveHandler(todo)}>
            {todo}
          </ul>
        ))}
      </ul>
    </React.Fragment>
  );
};


export default TodoRef;

view raw todoRef.tsx hosted with ❤ by GitHub

If you interested on hooks I wrote two other posts:

If you find something not correct please feel free to comment below.

Follow me on twitter @DZurico


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK