xxxxxxxxxx
import React from "react";
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount() {
this.myRef.current.focus();
}
render() {
return <input type="text" ref={this.myRef} />;
}
}
xxxxxxxxxx
import React, { useRef } from 'react';
function App() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
export default App;
xxxxxxxxxx
import React, { useRef } from 'react';
const MyComponent = () => {
// Create a ref object
const myRef = useRef();
// Accessing the reference to the element
const handleClick = () => {
console.log(myRef.current);
// Do something with the element reference
};
return (
<div>
{/* Assign the "ref" attribute to the element */}
<button ref={myRef} onClick={handleClick}>
Click me
</button>
</div>
);
};
export default MyComponent;
xxxxxxxxxx
// bad
<Foo
ref="myRef"
/>
// good
<Foo
ref={(ref) => { this.myRef = ref; }}
/>
xxxxxxxxxx
inputRef = React.createRef<HTMLInputElement>();
divRef = React.createRef<HTMLDivElement>();