3

The code below throws a typeerror: 'Cannot read property "focus" of null'. Going off of react's documentation this should work. NOTE: The parent component implements redux connect method, but I'm not sure why this would have any effect on this component.

import React, { Component, createRef } from 'react';
import './Card.scss';

const Card = ({isEditing, item, onBlur, onChange}) => {
  let inputText = createRef();

  const editing = (editMode) => {
    if (editMode) {
      inputText.current.focus();
    }

    return e => {
      e.stopPropagation();
      isEditing(item, editMode);
    };
  }

  const update = () => {
    return e => {
      onChange(item.id, e.target.value);
    }
  }

  return (
    <div className="card">
      <img className="card-image" src="https://picsum.photos/200/200" 
        alt="no image display" />
      <div className="card-body">
        {item.edited ? (
          <div>
            <input type="text" ref={inputText} onClick={e => 
            e.stopPropagation()} value={item.name} onBlur= 
            {editing(false)} 
            onChange= 
            {update()} />
        </div>
      ) : (
        <h3 className="card-title" onClick={editing(true)} >
          {item.name}
        </h3>
      )}
      </div>
    </div>
   );
  }

export default Card;
Joseph Williams
  • 85
  • 1
  • 15
  • Possible duplicate of [React stateless component this.refs..value?](https://stackoverflow.com/questions/37266411/react-stateless-component-this-refs-value) – Roy Wang May 09 '18 at 02:14

2 Answers2

6

Please, use useRef as described here.

This function creates mutable object that is active during functional component lifecycle.

SunleoSun
  • 61
  • 1
  • 1
3

Problem could be this line:

<h3 className="card-title" onClick={editing(true)} >

Probably what you wanted to do would be something like onClick={() => {editing(true)}}

and since first input where you set the ref is not initially rendered, the current is never set.

erich
  • 261
  • 5
  • 12
  • 3
    The doc says you cannot assign refs **to** Functional components, not that you can't use then inside them. – Dane Feb 25 '19 at 18:36
  • to further what @Dane added, you can use ref on the functional components using forwardRef – Heyflynn Apr 03 '19 at 12:46