how to use ref in functional component code example
Example 1: cre&atRefs react js
const node = this.myRef.current;
Example 2: ref in functional components
function MyFunctionComponent() { return <input />;
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef(); }
render() {
return (
<MyFunctionComponent ref={this.textInput} /> );
}
}
Example 3: use ref in component reactjs
function MyFunctionComponent() { return <input />;
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef(); }
render() {
return (
<MyFunctionComponent ref={this.textInput} /> );
}
}
Example 4: use ref in component reactjs
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef(); }
componentDidMount() {
this.textInput.current.focusTextInput(); }
render() {
return (
<CustomTextInput ref={this.textInput} /> );
}
}
Example 5: use ref in component reactjs
function CustomTextInput(props) {
function handleClick() {
textInput.current.focus(); }
return (
<div>
<input
type="text"
ref={textInput} /> <input
type="button"
value="Donner le focus au champ texte"
onClick={handleClick}
/>
</div>
);
}
Example 6: use ref in component reactjs
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = null;
this.setTextInputRef = element => { this.textInput = element; };
this.focusTextInput = () => {
componentDidMount() {
this.focusTextInput(); }
render() {
return (
<div>
<input
type="text"
ref={this.setTextInputRef} />
<input
type="button"
value="Donner le focus au champ texte"
onClick={this.focusTextInput} />
</div>
);
}
}