React – Call function from HTML Tag with parameter

ReactSometimes we need to call a React function from HTML tags with parameters or arguments and following is the ES6 based way.

Here a button is calling a function updateName with argument newName to set a state which in turns changes the name being displayed.

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';

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

  updateName = (newName) =>{
    this.setState({
      name: newName
    })
  }

  render() {
    return (
      <div>
        <p>My Name is {this.state.name}.</p>
        <p>          
          <button onClick={this.updateName.bind(this,'Kannan Balasubramanian')}>Change the name</button><br/>
          <button onClick={()=>this.updateName('Kannan Balasubramanian!')}>Change the name again</button>
        </p>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

Do note that using this.updateName.bind() is the recommended way due to performance and efficiency concerns.

You can try the sample output here.


Leave a Reply

Your email address will not be published / Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.