'React 18 useId cannot be in key
The error: React Hook "useId" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function. So, question, where we can use useId()? I also got the same id for my mapped divs with the code:
// @ts-ignore
import React, {useRef, useState, useId} from 'react';
interface InputLocationProps {
cleanAddress(): void
}
export const InputLocation: React.FC<InputLocationProps> = ({cleanAddress}) => {
const id = useId()
const ref = useRef<HTMLInputElement>(null);
const [text, setText] = useState<string>('');
const [textArray, setTextArray] = useState<string[]>(['more']);
const changeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
setText(event.target.value)
}
const putTextInArray = (puttingText: string) => {
setTextArray(prevState => [ ...prevState, puttingText])
}
const keyPressHandler = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter') {
event.preventDefault();
putTextInArray(text)
console.log(ref.current!.value)
ref.current!.value = '';
setText('');
cleanAddress();
}
}
return (
<form>
<label htmlFor="count">{text}</label>
<input ref={ref} onChange={changeHandler} onKeyPress={keyPressHandler} type="text" id="count"/>
{textArray.map(textArrayItem => {
return <div key={useId()}>{textArrayItem}</div>
})}
</form>
);
};
Solution 1:[1]
According documentation:
const Component = () => {
// outside callback
const id = useId();
return array.map((item, index) => <div key={`${id}-${index}`}>some content</div>
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | zemil |