'Manipulating the DOM with Refs'·续
import { useState, useRef } from 'react';
import { flushSync } from 'react-dom';
export default function TodoList() {
const listRef = useRef(null);
const [text, setText] = useState('');
const [todos, setTodos] = useState(
initialTodos
);
function handleAdd() {
const newTodo = { id: nextId++, text: text };
flushSync(() => {
setText('');
setTodos([ ...todos, newTodo]);
});
listRef.current.lastChild.scrollIntoView({
behavior: 'smooth',
block: 'nearest'
});
}
return (
<>
<button onClick={handleAdd}>
Add
</button>
<input
value={text}
onChange={e => setText(e.target.value)}
/>
<ul ref={listRef}>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
</>
);
}
let nextId = 0;
let initialTodos = [];
for (let i = 0; i < 20; i++) {
initialTodos.push({
id: nextId++,
text: 'Todo #' + (i + 1)
});
}
Best practices for DOM manipulation with refs
Refs are an escape hatch. You should only use them when you have to "step outside React". Common examples of this include managing focus, scroll position, or calling browser APIs that React does not expose.
If you stick to non-destructive actions like focusing and scrolling, you shouldn't encounter any problems. However, if you try to modify the DOM manually, you can risk conflicting with the changes React is making.
To illustrate this problem, this example includes a welcome message and two buttons. The first button toggles its presence using conditional rendering and state, as you would usually do in React. The second button uses the remove() DOM API to forcefully remove it from the DOM outside of React's control.
Try pressing "Toggle with setState" a few times. The message should disappear and appear again. Then press "Remove from the DOM". This will forcefully remove it. Finally, press "Toggle with setState":
import { useState, useRef } from 'react';
export default function Counter() {
const [show, setShow] = useState(true);
const ref = useRef(null);
return (
<div>
<button
onClick={() => {
setShow(!show);
}}>
Toggle with setState
</button>
<button
onClick={() => {
ref.current.remove();
}}>
Remove from the DOM
</button>
{show && <p ref={ref}>Hello world</p>}
</div>
);
}
p,
button {
display: block;
margin: 10px;
}
After you've manually removed the DOM element, trying to use setState to show it again will lead to a crash. This is because you've changed the DOM, and React doesn't know how to continue managing it correctly.
Avoid changing DOM nodes managed by React. Modifying, adding children to, or removing children from elements that are managed by React can lead to inconsistent visual results or crashes like above.
However, this doesn't mean that you can't do it at all. It requires caution. You can safely modify parts of the DOM that React has no reason to update. For example, if some <div> is always empty in the JSX, React won't have a reason to touch its children list. Therefore, it is safe to manually add or remove elements there.
- Refs are a generic concept, but most often you'll use them to hold DOM elements.
- You instruct React to put a DOM node into
myRef.currentby passing<div ref={myRef}>. - Usually, you will use refs for non-destructive actions like focusing, scrolling, or measuring DOM elements.
- A component doesn't expose its DOM nodes by default. You can opt into exposing a DOM node by using the
refprop. - Avoid changing DOM nodes managed by React.
- If you do modify DOM nodes managed by React, modify parts that React has no reason to update.
Play and pause the video
In this example, the button toggles a state variable to switch between a playing and a paused state. However, in order to actually play or pause the video, toggling state is not enough. You also need to call play() and pause() on the DOM element for the <video>. Add a ref to it, and make the button work.
import { useState, useRef } from 'react';
export default function VideoPlayer() {
const [isPlaying, setIsPlaying] = useState(false);
function handleClick() {
const nextIsPlaying = !isPlaying;
setIsPlaying(nextIsPlaying);
}
return (
<>
<button onClick={handleClick}>
{isPlaying ? 'Pause' : 'Play'}
</button>
<video width="250">
<source
src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"
type="video/mp4"
/>
</video>
</>
)
}
button { display: block; margin-bottom: 20px; }
For an extra challenge, keep the "Play" button in sync with whether the video is playing even if the user right-clicks the video and plays it using the built-in browser media controls. You might want to listen to onPlay and onPause on the video to do that.
Declare a ref and put it on the <video> element. Then call ref.current.play() and ref.current.pause() in the event handler depending on the next state.
import { useState, useRef } from 'react';
export default function VideoPlayer() {
const [isPlaying, setIsPlaying] = useState(false);
const ref = useRef(null);
function handleClick() {
const nextIsPlaying = !isPlaying;
setIsPlaying(nextIsPlaying);
if (nextIsPlaying) {
ref.current.play();
} else {
ref.current.pause();
}
}
return (
<>
<button onClick={handleClick}>
{isPlaying ? 'Pause' : 'Play'}
</button>
<video
width="250"
ref={ref}
onPlay={() => setIsPlaying(true)}
onPause={() => setIsPlaying(false)}
>
<source
src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"
type="video/mp4"
/>
</video>
</>
)
}
button { display: block; margin-bottom: 20px; }
In order to handle the built-in browser controls, you can add onPlay and onPause handlers to the <video> element and call setIsPlaying from them. This way, if the user plays the video using the browser controls, the state will adjust accordingly.
Focus the search field
Make it so that clicking the "Search" button puts focus into the field.
export default function Page() {
return (
<>
<nav>
<button>Search</button>
</nav>
<input
placeholder="Looking for something?"
/>
</>
);
}
button { display: block; margin-bottom: 10px; }
Add a ref to the input, and call focus() on the DOM node to focus it:
import { useRef } from 'react';
export default function Page() {
const inputRef = useRef(null);
return (
<>
<nav>
<button onClick={() => {
inputRef.current.focus();
}}>
Search
</button>
</nav>
<input
ref={inputRef}
placeholder="Looking for something?"
/>
</>
);
}
button { display: block; margin-bottom: 10px; }
Scrolling an image carousel
This image carousel has a "Next" button that switches the active image. Make the gallery scroll horizontally to the active image on click. You will want to call scrollIntoView() on the DOM node of the active image:
node.scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'center'
});
You don't need to have a ref to every image for this exercise. It should be enough to have a ref to the currently active image, or to the list itself. Use flushSync to ensure the DOM is updated before you scroll.
import { useState } from 'react';
export default function CatFriends() {
const [index, setIndex] = useState(0);
return (
<>
<nav>
<button onClick={() => {
if (index < catList.length - 1) {
setIndex(index + 1);
} else {
setIndex(0);
}
}}>
Next
</button>
</nav>
<div>
<ul>
{catList.map((cat, i) => (
<li key={cat.id}>
<img
className={
index === i ?
'active' :
''
}
src={cat.imageUrl}
alt={'Cat #' + cat.id}
/>
</li>
))}
</ul>
</div>
</>
);
}
const catCount = 10;
const catList = new Array(catCount);
for (let i = 0; i < catCount; i++) {
const bucket = Math.floor(Math.random() * catCount) % 2;
let imageUrl = '';
switch (bucket) {
case 0: {
imageUrl = "https://placecats.com/neo/250/200";
break;
}
case 1: {
imageUrl = "https://placecats.com/millie/250/200";
break;
}
case 2:
default: {
imageUrl = "https://placecats.com/bella/250/200";
break;
}
}
catList[i] = {
id: i,
imageUrl,
};
}
div {
width: 100%;
overflow: hidden;
}
nav {
text-align: center;
}
button {
margin: .25rem;
}
ul,
li {
list-style: none;
white-space: nowrap;
}
li {
display: inline;
padding: 0.5rem;
}
img {
padding: 10px;
margin: -10px;
transition: background 0.2s linear;
}
.active {
background: rgba(0, 100, 150, 0.4);
}
You can declare a selectedRef, and then pass it conditionally only to the current image:
<li ref={index === i ? selectedRef : null}>
When index === i, meaning that the image is the selected one, the <li> will receive the selectedRef. React will make sure that selectedRef.current always points at the correct DOM node.
Note that the flushSync call is necessary to force React to update the DOM before the scroll. Otherwise, selectedRef.current would always point at the previously selected item.
import { useRef, useState } from 'react';
import { flushSync } from 'react-dom';
export default function CatFriends() {
const selectedRef = useRef(null);
const [index, setIndex] = useState(0);
return (
<>
<nav>
<button onClick={() => {
flushSync(() => {
if (index < catList.length - 1) {
setIndex(index + 1);
} else {
setIndex(0);
}
});
selectedRef.current.scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'center'
});
}}>
Next
</button>
</nav>
<div>
<ul>
{catList.map((cat, i) => (
<li
key={cat.id}
ref={index === i ?
selectedRef :
null
}
>
<img
className={
index === i ?
'active'
: ''
}
src={cat.imageUrl}
alt={'Cat #' + cat.id}
/>
</li>
))}
</ul>
</div>
</>
);
}
const catCount = 10;
const catList = new Array(catCount);
for (let i = 0; i < catCount; i++) {
const bucket = Math.floor(Math.random() * catCount) % 2;
let imageUrl = '';
switch (bucket) {
case 0: {
imageUrl = "https://placecats.com/neo/250/200";
break;
}
case 1: {
imageUrl = "https://placecats.com/millie/250/200";
break;
}
case 2:
default: {
imageUrl = "https://placecats.com/bella/250/200";
break;
}
}
catList[i] = {
id: i,
imageUrl,
};
}
div {
width: 100%;
overflow: hidden;
}
nav {
text-align: center;
}
button {
margin: .25rem;
}
ul,
li {
list-style: none;
white-space: nowrap;
}
li {
display: inline;
padding: 0.5rem;
}
img {
padding: 10px;
margin: -10px;
transition: background 0.2s linear;
}
.active {
background: rgba(0, 100, 150, 0.4);
}
Focus the search field with separate components
Make it so that clicking the "Search" button puts focus into the field. Note that each component is defined in a separate file and shouldn't be moved out of it. How do you connect them together?
You'll need to pass ref as a prop to opt into exposing a DOM node from your own component like SearchInput.
```js src/App.js import SearchButton from './SearchButton.js'; import SearchInput from './SearchInput.js';
export default function Page() { return ( <>
```js src/SearchButton.js
export default function SearchButton() {
return (
<button>
Search
</button>
);
}
```js src/SearchInput.js export default function SearchInput() { return ( ); }
```css
button { display: block; margin-bottom: 10px; }
You'll need to add an onClick prop to the SearchButton, and make the SearchButton pass it down to the browser <button>. You'll also pass a ref down to <SearchInput>, which will forward it to the real <input> and populate it. Finally, in the click handler, you'll call focus on the DOM node stored inside that ref.
```js src/App.js import { useRef } from 'react'; import SearchButton from './SearchButton.js'; import SearchInput from './SearchInput.js';
export default function Page() { const inputRef = useRef(null); return ( <>
```js src/SearchButton.js
export default function SearchButton({ onClick }) {
return (
<button onClick={onClick}>
Search
</button>
);
}
```js src/SearchInput.js export default function SearchInput({ ref }) { return ( ); }
```css
button { display: block; margin-bottom: 10px; }
