Manzana
Manzana

Reputation: 325

Should I use createRef or useRef and why?

In this component I'm not sure if I should use createRef and useRef to get the information from the input. Can you please help me figuring out how I should choose one or the other? Thanks in advance

import React from 'react'

const AddBook = (props) => {

    const handleNewBook = props.handle
    let titleInput = React.createRef();
    let authorInput = React.createRef();

    return (
      <div className="add-book">
        <span className="add-book-title">Add a book:</span>
        <form>
          <input type="text" ref={titleInput} placeholder="Title" />
          <input type="text" ref={authorInput} placeholder="Author" />
          <button
            type="reset"
            onClick={() =>
              handleNewBook(titleInput.current.value, authorInput.current.value)
            }
          >
            Add
          </button>
        </form>
      </div>
    );
}

export default AddBook

Upvotes: 2

Views: 3299

Answers (2)

HichamELBSI
HichamELBSI

Reputation: 1719

For the difference between useRef and createRef: What's the difference between `useRef` and `createRef`?

Anyway, in your case, if you need a controlled input you should deal with the component state:

import React, { useState } from 'react';

const AddBook = (props) => {

    const handleNewBook = props.handle
    const [state, setState] = useState({})

    return (
      <div className="add-book">
        <span className="add-book-title">Add a book:</span>
        <form>
          <input type="text" value={state.title} onChange={e => setState(prev => ({...prev, title: e.target.value}))} placeholder="Title" />
          <input type="text" value={state.author} onChange={e => setState(prev => ({...prev, author: e.target.value}))} placeholder="Author" />
          <button
            type="reset"
            onClick={() =>
              handleNewBook(state.title, state.author)
            }
          >
            Add
          </button>
        </form>
      </div>
    );
}

Upvotes: 2

YTG
YTG

Reputation: 1058

CreateRef is usually used in class components.

useRef (a hook that creates a ref) is used in functional components.

Since you are using functional best use useRef.

Upvotes: 6

Related Questions