Home > Software engineering >  Next JS - how to set random number as id in constructor
Next JS - how to set random number as id in constructor

Time:09-07

How can I fix the error below?

Error: Text content does not match server-rendered HTML.

See more info here: https://nextjs.org/docs/messages/react-hydration-error

Here's my code.

export class Card {                
    constructor(props) {              
        this.id = Math.random();    
    }
}

If I change the id to a static number like below, the error goes away but I need the id to be a random number.

export class Card {                
    constructor(props) {              
        this.id = 3
    }
}

CodePudding user response:

You should check when you're on the client side.

  1. The easiest way to find out is to use componentDidMount and set a state by creating the random number. In functional one, useEffect will be used.
  2. Another way is checking typeof window === 'undefined'. If it's false, so window exists and you can do what you want.

CodePudding user response:

Using Math.random() in the constructor will be invoked on a server and in the browser causing a mismatch in rendered markup.

You can Update the random in the componentDidMount or useEffect,

Refer.. Incorrect rendering of a component when using Math.random in setState in React Component

export class Card extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      id: 3,
    };
  }
  componentDidMount() {
    this.setState({
      id: Math.random(),
    });
  }
  render() {
    console.log(this.state.id);
    return this.state.id;
  }
}
  • Related