Udders Udders - 1 year ago 84
React JSX Question

Outputting variable in react component

I am trying to out a variable in a component however I am getting the following error,


Invalid regular expression: missing /


My code is as follows,

class Profile extends React.Component {
constructor() {
super();
this.state = {
user:user
}
this.updateAvatar = this.updateAvatar.bind(this);
this.formatName = this.formatName.bind(this);
}

render() {
let user_name = this.formatName(this.state.user.first_name, this.state.user.last_name);
console.log(user_name);
return (
<Avatar image={this.state.user.avatar}
changeImageOnClick={this.updateAvatar} />
<p>{ user_name }</p>
)
}

formatName(first_name, last_name) {
console.log(first_name);
return first_name + " " + last_name;
}

updateAvatar() {
this.setState({user:{avater:'new'}})
}
}


Cant understand why I would be getting this error, this should be so simple to do :(

Answer Source

You can't return two nodes on the same level. Just one, so you need to wrap it. Try this:

class Profile extends React.Component {
  constructor() {
    super();
    this.state = {
      user:user
    }
    this.updateAvatar = this.updateAvatar.bind(this);
    this.formatName = this.formatName.bind(this);
  }

  render() {
    let user_name = this.formatName(this.state.user.first_name, this.state.user.last_name);
    console.log(user_name);
    return (
      <div>
        <Avatar image={this.state.user.avatar}
                changeImageOnClick={this.updateAvatar} />
        <p>{ user_name }</p>
      </div>
    )
  }

  formatName(first_name, last_name) {
    console.log(first_name);
    return first_name + " " + last_name;
  }

  updateAvatar() {
      this.setState({user:{avater:'new'}})
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download