Home > Mobile >  How to add a callback and a function at the same time in a single onClick in React?
How to add a callback and a function at the same time in a single onClick in React?

Time:03-15

I have a button that has a callback function in which I want to add another function that plays music. How do I do this?

My code:

import React from 'react';
import { Howl } from 'howler';

const StartButton = ({ callback }) => {
    function sound() {
        const sound = new Howl( {
            src: [ 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3'],
            html5: true,
        });

    }
    return (
        <div className='button' onClick={()=>{ sound(); callback}}>Start Game</div>
    );
}

export default StartButton; 

I have an error after running the code above: Expected an assignment or function call and instead saw an expression no-unused-expressions

CodePudding user response:

You forgot to invoke the function itself

import React from 'react';
import { Howl } from 'howler';

const StartButton = ({ callback }) => {
  function sound() {
    const sound = new Howl({
      src: [ 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3' ],
      html5: true
    });
  }

  return (
    <div className="button"
        onClick={ () => {
          sound();
          callback(); // <== HERE
        } }>
      Start Game
    </div>
  );
};

export default StartButton;

I would suggest that you put that inside the sound function and not to create another function in the onClick event, it could be cleaner

import React from 'react';
import { Howl } from 'howler';

const StartButton = ({ callback }) => {
  function sound() {
    const sound = new Howl({
      src: [ 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3' ],
      html5: true
    });

    callback();
  }

  return (
    <div className="button" onClick={ sound }>
      Start Game
    </div>
  );
};

export default StartButton;

CodePudding user response:

l get you but onClick is not support this arguments. you can code like this

onClick={() => { sound()}}

function sound() {
  ...
  callback() 
}
function callback() {
  ...
}
  • Related