React. how to pass props from onClick to function
Asked Answered
M

1

11

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 a 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 are no props being passed down.

How can I fix that?

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.

Michale answered 26/11, 2017 at 14:17 Comment(0)
S
18

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 ?

Striptease answered 26/11, 2017 at 15:28 Comment(1)
Oh my dear lord. The solution is so simple. I have been pondering over this for the whole day. Thank you a thousand times.Michale

© 2022 - 2024 — McMap. All rights reserved.