Home > Blockchain >  How to set the next state values based on previous values in React?
How to set the next state values based on previous values in React?

Time:06-24

Here is an example:

class MyComp extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      firstName: 'xyz',
      lastName: 'abc';
      fullName: firstName   lastName
    };
  }

Trying the above technique gives me errors. I also tried using this.firstName and this.lastName but that also resulted in errors. How should I proceed?

Thanks.

CodePudding user response:

you should use this.state.firstname.....

because you use state in constructor and if you want to access that item you have to define this.state.'your item name'

class MyComp extends React.Component {

constructor(props) { super(props);

const firstName = 'xyz';
const lastName = 'abc';

this.state = {
  firstName,
  lastName,
  fullName: firstName   lastName
};

}

on this you can use this.state.firstname

CodePudding user response:

You can try as below

class MyComp extends React.Component {
  constructor(props) {
    super(props);
    
    const firstName = 'xyz';
    const lastName = 'abc';
    
    this.state = {
      firstName,
      lastName,
      fullName: firstName   lastName
    };
  }

  • Related