Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!