Part 1
Folder Structure
App.js Code
import { useState, useRef } from 'react';
import CustomInput from './CustomInput';
export default function App() {
const [value, setValue] = useState("red");
const inputRef = useRef();
return (
<>
{/* <input
ref={inputRef}
value={value}
onChange={(e) => setValue(e.target.value)}
/> */}
<CustomInput
ref={inputRef}
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<br />
<button onClick={() => inputRef.current.focus()}> Focus </button>
</>
)
}
CustomInput.js
import React from 'react'
function CustomInput(props, ref) {
return (
<input {...props} ref={ref} />
)
}
export default React.forwardRef(CustomInput);
Output
Part 2
App.js Code
import { useState, useRef } from 'react';
import CustomInput from './CustomInput';
export default function App() {
const [value, setValue] = useState("red");
const inputRef = useRef();
return (
<>
{/* <input
ref={inputRef}
value={value}
onChange={(e) => setValue(e.target.value)}
/> */}
<CustomInput
ref={inputRef}
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<br />
<button onClick={() => inputRef.current.alertHi()}> Focus </button>
</>
)
}
CustomInput.js
import React, { useImperativeHandle } from 'react'
function CustomInput(props, ref) {
useImperativeHandle(
ref,
() => {
return { alertHi: () => alert(props.value) }
},
[props.value]
)
return (
<input {...props} />
)
}
export default React.forwardRef(CustomInput);
Output
Part 3
App.js Code
import { useState, useRef } from 'react';
import ConfirmationModel from './ConfirmationModel';
function App() {
const [open, setOpen] = useState(false);
const modelRef = useRef();
return (
<>
<button onClick={() => setOpen(true)}> Open </button>
<button onClick={() => modelRef.current.focusCloseBtn()}> Focus Close </button>
<button onClick={() => modelRef.current.focusConfirmBtn()}> Focus Confirm </button>
<button onClick={() => modelRef.current.focusDenyBtn()}> Focus Deny </button>
<ConfirmationModel ref={modelRef} isOpen={open} onClose={() => setOpen(false)} />
</>
)
}
export default App;
ConfirmationModel.js
import { useRef, forwardRef, useImperativeHandle } from 'react'
const ConfirmationModel = ({ isOpen, onClose }, ref) => {
const closeRef = useRef();
const denyRef = useRef();
const confirmRef = useRef();
useImperativeHandle(
ref,
() => {
return {
focusCloseBtn: () => closeRef.current.click(),
focusConfirmBtn: () => denyRef.current.click(),
focusDenyBtn: () => confirmRef.current.click(),
}
},
[]
)
if (!isOpen) return null;
return (
<div >
<button ref={closeRef} onClick={console.log(1)}>
×
</button>
<div>
<h1> Title </h1>
</div>
<div >Do you Confirm ?</div>
<div>
<button ref={confirmRef} onClick={onClose}>
yes
</button>
<button ref={denyRef} onClick={onClose}>
No
</button>
</div>
</div>
)
}
export default forwardRef(ConfirmationModel);
Output
Top comments (0)