I have a react component that receives an id from its props.
export type MyComponentProps = {
id: string
}
export const MyComponent = function(props: MyComponentProps) {
return (
<div>{props.id}</div>
);
}
Now, I want to make the id optional, but I do have a requirement to use identifiers so I make the id as optional and add a default prop.
import { v4 } from 'uuid';
export type MyComponentProps = {
id?: string
}
export const MyComponent = function(props: MyComponentProps) {
return (
<div>{props.id}</div>
);
}
MyComponent.defaultProps = {
id: `MyComponent-${v4()}`
}
Done! Except, now, if I render 2 different instances of MyComponent they will have the same id. How do I work around this? What I did is the following, but I am no react expert and I don't know if there is another way to accomplish this.
import { v4 } from 'uuid';
export type MyComponentProps = {
id?: string
}
export const MyComponent = function(props: MyComponentProps) {
const id = props.id?? `MyComponent-${v4()}`;
return (
<div>{id}</div>
);
}