Home > database >  How to run a function using onClick in React
How to run a function using onClick in React

Time:10-12

When I press the sync button, I need to run the Check Routine function. How can I do this ?

const CheckRoutine = require('../routines/check-at');

export default ({ className }) => (
  <ul className={ `nav flex-column ${className || ''}` }>
    <li>
      <button className="btn btn-primary" 
        onClick={CheckRoutine} >
        <i className="fa fa-refresh"> </i>
        <span>Sync</span>
      </button>
    </li>
  </ul>
);```



check-at:

module.exports = atCheck;
function atCheck() {
  console.log("Cheking...");
}

CodePudding user response:

If your check Routine is in the same component, you can directly give,

<button className="btn btn-primary" 
        onClick={CheckRoutine} >
        <i className="fa fa-refresh"> </i>
        <span>Sync</span>
      </button>

or If your Check routine is in parent component, you can use call back function inside your component like below.

const CheckRoutine =(event) =>{
event.preventDefault();
props.checkRoutine();
}

<button className="btn btn-primary" 
        onClick={CheckRoutine} >
        <i className="fa fa-refresh"> </i>
        <span>Sync</span>
      </button>

CodePudding user response:

import atCheck from '../routines/check-at'

export default ({ className }) => (
<ul className={ `nav flex-column ${className || ''}` }>
    <li>
      <button className="btn btn-primary" 
        onClick={atCheck} >
        <i className="fa fa-refresh"> </i>
        <span>Sync</span>
      </button>
    </li>
  </ul>
);

//../routines/check-at

export default const atCheck => (e) {
  console.log("Cheking...");
}

CodePudding user response:

you can use this,

CheckRoutine.js
const CheckRoutine = e => {
console.log(e)
}
export default CheckRoutine


fileName.js
import CheckRoutine from './CheckRoutine'

export default ({ className }) => (
  <ul className={ `nav flex-column ${className || ''}` }>
    <li>
      <button className="btn btn-primary" 
        onClick={CheckRoutine} >
        <i className="fa fa-refresh"> </i>
        <span>Sync</span>
      </button>
    </li>
  </ul>
);

or you can in single file

const CheckRoutine = e => {
 console.log(e)
}
export default ({ className }) => (
  <ul className={ `nav flex-column ${className || ''}` }>
    <li>
      <button className="btn btn-primary" 
        onClick={CheckRoutine} >
        <i className="fa fa-refresh"> </i>
        <span>Sync</span>
      </button>
    </li>
  </ul>
);
  • Related