react hook form and headlessui ref is not available #11150
Answered
by
mutasim77
gangadharjannu
asked this question in
Q&A
-
We are using I setup a codesandbox to explain the issue. https://codesandbox.io/s/react-hook-form-v7-controller-forked-fr9dsn?file=/src/index.js Can you help me how to get |
Beta Was this translation helpful? Give feedback.
Answered by
mutasim77
Nov 7, 2023
Replies: 1 comment 1 reply
-
index.jsimport React, { useRef } from "react";
import ReactDOM from "react-dom";
import { useForm, Controller } from "react-hook-form";
import { MyCombobox } from "./MyCombobox";
function App() {
const statusRef = useRef(null); // Create a ref
const { control, handleSubmit } = useForm({
defaultValues: {},
mode: "all"
});
return (
<form
onSubmit={handleSubmit((data) => {
console.log(data);
})}
className="form"
>
<Controller
name="status"
control={control}
rules={{
required: {
value: true,
message: "hiello error"
}
}}
render={({ field }) => {
// Store the ref of the input element in the statusRef
const inputRef = statusRef;
return (
<>
<div style={{ position: "absolute", top: "1000px" }}>
<MyCombobox
field={field}
selected={field.value}
setSelected={field.onChange}
label="Status"
placeholder="[Choose]"
options={[]}
errorMessage="status"
// Pass the ref to the MyCombobox component
inputRef={inputRef}
/>
</div>
<button
onClick={() => {
console.log(inputRef.current); // the the console
if (inputRef.current) {
inputRef.current.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "start"
});
}
}}
>
Scroll to elem
</button>
</>
);
}}
/>
</form>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement); MyCombobox.jsimport React from "react";
import { useState } from "react";
import { Combobox } from "@headlessui/react";
const people = [
{ id: 1, name: "Durward Reynolds" },
{ id: 2, name: "Kenton Towne" },
{ id: 3, name: "Therese Wunsch" },
{ id: 4, name: "Benedict Kessler" },
{ id: 5, name: "Katelyn Rohan" }
];
export function MyCombobox({ field, inputRef }) {
const [selectedPerson, setSelectedPerson] = useState(people[0]);
const [query, setQuery] = useState("");
const filteredPeople =
query === ""
? people
: people.filter((person) => {
return person.name.toLowerCase().includes(query.toLowerCase());
});
return (
<Combobox
as="div"
{...field}
ref={inputRef} // ref here
value={selectedPerson}
onChange={setSelectedPerson}
>
<Combobox.Input
onChange={(event) => setQuery(event.target.value)}
displayValue={(person) => person.name}
/>
{/* Render a `div` instead of a `ul` */}
<Combobox.Options as="div">
{filteredPeople.map((person) => (
/* Render a `span` instead of a `li` */
<Combobox.Option as="span" key={person.id} value={person}>
{person.name}
</Combobox.Option>
))}
</Combobox.Options>
</Combobox>
);
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
gangadharjannu
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
index.js