H.Mirza
H.Mirza

Reputation: 11

Is there a simpler way to write this React code

Need this code more simplified. All I wanna do is have an onClick event perform an action, but the code seems overcomplicated for what I wanna do:

import React, { Component } from 'react';

class Comment extends Component{
    constructor(){

      super();
      this.state= {name:''};

      this.display = this.display.bind(this);
    }


display(){
  this.setState({name:'Test2'});
}

    render(){
      return(
        <div>
          <button onClick={this.display}>Click me</button>
          <h1>{this.state.name}</h1>
        </div>
      )
  }

}

export default Comment;

Upvotes: 1

Views: 35

Answers (2)

ravibagul91
ravibagul91

Reputation: 20765

If you don't want to try Hooks (Hooks are added in V16.8), then arrow function is also a simple one,

class Comment extends Component {
  constructor() {
    super()
    this.state = {name: ''}
  }

  render() {
    return (
      <div>
        <button onClick={() => this.setState({name: 'Test2'})}>Click me</button>
        <h1>{this.state.name}</h1>
      </div>
    )
  }
}

Demo

Upvotes: 0

Dacre Denny
Dacre Denny

Reputation: 30390

If you're using React 16.8, then a simpler implementation as a functional component based on the useState hook is possible like so:

import React, { useState } from 'react';

/* Define functional equivalent of Comment component */
const Comment = () => {

    /* Setup name state getter/setter via useState hook */
    const [name, setName] = useState('')

    /* Render comment JSX */
    return (<div>
        <button onClick={() => setName('Test2')}>Click me</button>
        <h1>{name}</h1>
    </div>)
}

export default Comment;

Upvotes: 3

Related Questions