Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
How to use different default props in React?

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>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If you want a per-component ID that stays the same between renders, you'll need to put it in state.

export const MyComponent = function(props: MyComponentProps) {
  const [defaultId] = useState(v4)
  const id = props.id ?? defaultId
  return (
    <div>{id}</div>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda