Current section: Focus Management 36 exercises
solution

flushSync

Loading solution

Transcript

00:00 To get started, let's handle the case where when I click on it, it turns into an input, but I want to select all the text. I want to be focused on there. So we're going to wrap this in a flush sync from React DOM, so that the edit gets turned to true,

00:19 and we render this form instead of the button. So that's going to happen instantly, and now we'll have the button. So we can say input ref.current.select, and that will select all the text. Of course, if we select all the text, then we're going to be focused on the input. So click, boom, look at that.

00:36 That's so good. Awesome. Okay, so let's move on to the next thing. Now we're on the input. If I blur the input, then I should focus on the button. That would make sense. The button isn't there yet, so we got a flush sync to make it so that the button appears

00:55 right away right after we're finished updating the value and setting edit to false. So once that happens, we can say, oh, we need a button ref, right? We need access to the button. So let's say ref equals button ref.

01:10 Come up here and make a button ref right there, and then with this, we can say focus on the button when we blur. So coming over here, focus on this. I click on it, and I type something,

01:29 and then I blur, and boom, look at me. I'm on the button. Amazing. So good. So, so good. All right, great. So now on key down. So if I'm moving around and then I type space, or maybe I type, actually, I'm on the input, I type escape,

01:47 then that should also focus on the button. So let's wrap this in a flush sync. Set edit to false and focus on the button. Beautiful. So now I'm coming over here. I type something and I hit escape. Then we're basically quitting. We're just like, oh, never mind, cancel.

02:07 Now we're focused on the button, so we can type it again. Oh my gosh. So good. So good. Okay, great. So when we submit, so I type something and I hit enter, I should also focus on the button. So let's wrap this in flush sync

02:28 and focus on the button. And so I type in super duper neat and hit enter. I'm focused on the button. So fantastic. Well done, you. I love it. Love it to pieces. Yep. Such a good experience. All right.

02:50 I like being able to use my keyboard around applications and I'm just a power user. There are users out there who cannot use a mouse for one reason or another and we should make awesome experiences for them too. So I'm glad that we have flush sync as a mechanism for us providing those awesome experiences. I hope that was fun and exciting for you.

03:09 Well done.