12

I have a problem with ref and conditional rendering. I would like to focus an input tag when I click on a button tag. Basically, I have this simplified code.

class App extends React.Component {
  textInput
  constructor(props) {
    super(props)
    this.state = {isEditing: false}
    this.textInput = React.createRef()
  }

    onClick = () => {
        this.setState({isEditing: !this.state.isEditing})
        this.textInput.current.focus();
    }
  render () {
    let edit = this.state.isEditing ?
        (<input type="text" ref={this.textInput} />)
        : ""
    return (
      <div>
            <button onClick={this.onClick}>lorem </button>
            {edit}
      </div>
    );
  }
}

When I click on the button, the input tag is displayed but the ref textInput is still set to null. Thus I can't focus the input.

I found some workaround like:

  • set autoFocus property in the input tag
  • hide the input tag with css when isEditing == false

But actually it is a very basic pattern and I would like to know if there is a clean solution.

Thank you

2 Answers 2

14

TL;DR:

Change this:

this.setState({isEditing: !this.state.isEditing})
this.textInput.current.focus();

to this:

this.setState(previousState => ({isEditing: !previousState.isEditing}), () => {
    this.textInput.current.focus();    
});

Update: Functional Components / Hooks

It's been asked in the comments how to do this with useState and functional components. Rafał Guźniczak's answer explains it, but I wanted to provide a bit more explanation and a runnable example.

You still don't want to read state immediately after setting it, but instead of using a second argument callback to setState, you need to run some code after the state is updated and the component has re-rendered. How do we do that?

The answer is useEffect. The purpose of effects are to synchronize external "things" (for example: imperative DOM things like focus) with React state:

const { useEffect, useRef, useState } = React;
const { render } = ReactDOM;

function App(props) {
  const [isEditing, setIsEditing] = useState(false);
  const textInputRef = useRef(null);

  const toggleEditing = () => setIsEditing(val => !val);

  // whenever isEditing gets set to true, focus the textbox
  useEffect(() => {
    if (isEditing && textInputRef.current) {
      textInputRef.current.focus();
    }
  }, [isEditing, textInputRef]);

  return (
    <div>
      <button onClick={toggleEditing}>lorem </button>
      {isEditing && <input type="text" ref={textInputRef} />}
    </div>
  );
}

render(
  <App />,
  document.getElementById('root')
);
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div>


Details:

You're running into a common problem many people run into with React, which is the assumption that setting state is synchronous. It's not. When you call setState, you're requesting that React update the state. The actual state update happens later. This means that immediately after the setState call, the edit element hasn't been created or rendered yet, so the ref points to null.

From the docs:

setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.

Sign up to request clarification or add additional context in comments.

8 Comments

Added a bit more detail 👍
Got it, I didn't know that we can pass a function as an argument of setState
Yeah, it's usually not the way that most docs introduce setState, unfortunately. IMO the API should have only supported the two-function form, and probably should've been called setStateAsync, but unfortunately it's a bit late for that :(
@rossipedia, while your approach is still fine, I would suggest using the functional setState() here since the new state depends on the previous one. This is also recommended approach by the official docs.
hey nice job, how to get this with useState?
|
4

Thank a lot for your answer @rossipedia. I was wondering if I can do it with hooks.

And apparently you can't pass second parameter to useState setter as in setState. But you can use useEffect like this (note second parameter in useEffect):

const [isEditing, setIsEditing] = React.useState(false);
React.useEffect(() => {
    if (isEditing) {
        textInput.current.focus();
    }
}, [isEditing]);

const handleClick = () => setIsEditing(isEditing);

And it worked! ;)

Source: https://www.robinwieruch.de/react-usestate-callback/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.