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.
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
};
}
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
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
})
}