Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React. how to pass props from onClick to function

I am new to React, I am trying to create an app in which I can click on a button and a function will run countdown timer, but If I pass props from onClick to begin function like this, onClick={begin(props.subject)} the function will run before I click. and if I use onClick with begin without argument, there is no props being passed down. how can I fix that? thanks

import React from 'react';
import SubjectForm from './SubjectForm';

const EditSubject=(props)=>{
    return(
        <div>
        <button onClick={begin}>start</button>
        </div>)
};

const begin = (props)=> {
   console.log(props.subject)
}

const mapStateToProps=()=>{};

export default connect(mapStateToProps)(EditSubject);

also, is there a way or trick to use a variable inside of begin function from an outside function? so I can make a pause button to pause seInterval in begin function.

like image 431
Nhat Avatar asked Nov 26 '17 14:11

Nhat


1 Answers

You are using functional (stateless) components in this example. You can also use ES6 classes to represent React components, with functions being methods of the class. Then you may make functions like begin in your code as class methods, so they can access class data members like props.
See the code below:

import React from 'react';
import SubjectForm from './SubjectForm';

class EditSubject extends React.Component {
  constructor() {
    super();
    this.begin = this.begin.bind(this);
  }
  begin() {
     console.log(this.props.subject);
  }
  render() {
    return (
        <div>
          <button onClick={begin}>start</button>
        </div>
    );
  }
};

const mapStateToProps=()=>{};

export default connect(mapStateToProps)(EditSubject);

This is just a best practice if your component has states, and methods. Using functional components like in your example, you may use simply the following:

const EditSubject = (props) => {
  return (
    <div>
      <button
        onClick={() => begin(props)}  // using props here
      >
        start
      </button>
    </div>
  );
};

Simple, right ?

like image 133
Dane Avatar answered Oct 20 '22 20:10

Dane