Redirect happens before onClick() on REACT { Link }
Hello. I'm trying the whole day to play a sound onClick Button Event. It works when I remove the Link (URL), but with the Link, the page goes to the new URL without firing the onClick event. I already tried like this: onClick={() => this.playAudioHandler}. I really appreciate if someone can fix my code in order to fire the “playAudioHandler” before going to the new URL.
This is my actual code:
import React, { Component } from "react";
import { Link } from "react-router-dom";
import classes from "./Button.module.css";
import clickSound from "../assets/click.mp3";
class Button extends Component {
playAudioHandler = (event) => {
const audioEl = document.getElementsByClassName("audio-element")[0];
audioEl.play();
// event.preventDefault();
};
render() {
return (
<>
<audio className="audio-element">
<source src={clickSound}></source>
</audio>
<Link to={this.props.linkToGo}>
<button
type="submit"
onClick={this.playAudioHandler}
className={[classes.Button, classes[this.props.btnType]].join(" ")}
// join() to transform the array in a string
>
{this.props.children}
</button>
</Link>
</>
);
}
}
export default Button;