3
votes

I have such js code:

let idCounter = 0;

export default class TestComponent extends Component {
  constructor(props) {
    super(props);

    this.uniqueId = `TestComponent-${idCounter++}`;
  }

  render() {
     return (<div id={this.uniqueId> Some content </div>);
  }
}

I need to have unique Id for every rendered element, so I count them. But I have SSR with Next.js. When the page initializes on the server then idCounter is incremented few times because of server rendering.

Then normal browser tries to render this component starting idCounter from 0 and replacing server-side rendered id (e.g. "TestComponent-5" to "TestComponent-0"). And I end up with error in console:

"Warning: Prop id did not match. Server: "TestComponent-5" Client: "TestComponent-0" "

I don't know how to handle that. Any ideas?

1

1 Answers

1
votes

I see that the question is pretty old already, but anyway, I've been struggling with this problem whole day until found the solution. And it doesn't seem like there are a lot of information about it.

There is a library named react-uid which is SSR friendly. You'll just need to wrap your app in UIDReset and use unique ids provided by UIDConsumer in components

/pages/index.tsx:

import { UIDConsumer } from 'react-uid'

...
const Index = () => {
  return (
    <>
      <UIDReset prefix="uid_">
        <Layout>
          <Head>
            <title>Next.js App</title>
          </Head>
          <MyComponent />
        </Layout>
      </UIDReset>
    </>
  )

/components/MyComponent.tsx

import { UIDConsumer } from 'react-uid'
...

return(
  <UIDConsumer>
    {(id) => (
      (<div id={id}> Some content </div>);
    )}
  </UIDConsumer>
)

Hope that still will be helpful.