How to use wavesurfer.js in React?
Asked Answered
P

1

7

i'm trying to render audio files using wavesurfer.js in my react app. I'm a noob and I'm wondering why I'm getting a "Container element not found" message all the time.

This is what i need to know in a nutshell.

THank you in advance!

import React from "react";
import WaveSurfer from "wavesurfer.js";

export default function Chat(){

  const wavesurfer = WaveSurfer.create({
    container: "#waveform",
  });
  
  render(
    <>
      <div id="waveform">
      </div>
    </>
  )
 }
Picklock answered 17/12, 2019 at 17:36 Comment(1)
You're trying to mount the javascript library into a div with the id "container", inside your render function, which runs before React generates the HTML and updates the DOM with a component with that ID. Put the call into a componentdidmount callbackKalif
U
13

You are currently calling that in the render function, which would mean it is executed everytime the component refreshes. Instead you can add it in a useEffect hook so that the waveform function is called only once and the element you are binding it to is present.

Also, you can use a ref instead of the ID, which is what React uses to refer to DOM elements.

import React, { useRef, useEffect } from "react";
import WaveSurfer from "wavesurfer.js";

export default function Chat(){
  const waveformRef = useRef();

  useEffect(() => {
    if(waveformRef.current) {
      const wavesurfer = WaveSurfer.create({
        container: waveformRef.current,
      });
    }
  }, []);
  
  return(
    <>
      <div ref={waveformRef}>
      </div>
    </>
  )
 }

useEffect Refs

Upper answered 17/12, 2019 at 17:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.