-1

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.

Real Noob
  • 1,369
  • 2
  • 15
  • 29

3 Answers3

-1

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
    };
  }
-1

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

-1

You can set after component mounted, if your scenario allows it.

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

then

 componentDidMount() {
    this.setState({
        fullName : this.firstName + this.lastName
    })
}