Search code examples
reactjstypescriptstorybook

Auto generate Id in React


I want to generate auto id with timestamp and use it in Label by using react. I have used Styled Component for < Label >

// Input Error Label
 const Label = styled.label`
  color: ${theme.colors.red.default};
  padding-top: 3px;
  display: inline-block;
  font-size: 14px;
  opacity: 0.55;
  mix-blend-mode: normal;
`;


const uniqueId = () => parseInt(Date.now() * Math.random()); 

return (
   <Label id={uniqueId}>{error}</Label>  
)

Why it shows error, please see this screenshot.

Error Screenshot

I hope this code helps.


Solution

  • You're trying to assign number as id when accepted type is string. Change your uniqueID function to this -

    const uniqueId = () => parseInt(Date.now() * Math.random()).toString();
    

    Also change your return function with this -

    return (
       <Label id={uniqueId()}>{error}</Label>  
    )
    

    A working code can be seen here

    https://codesandbox.io/s/compassionate-zhukovsky-wr3qi?file=/src/App.js