whitebear
whitebear

Reputation: 12423

Ref from class to functional component

I use ref from parent class to access child class.

However in this case I want to access from parent class to child functional component.

in parent class.

class Waveform extends Component {

  constructor(props){
    super(props);
    this.track_0Ref = React.createRef();
  }
  handlePlay = () => {
    console.log("play button click");
    var node = this.track_0Ref.current
    console.log(node); //  show null......
  }
  render() {
    return (
      <AudioTrack trackNum="0" ref={this.track_0Ref}/>
    )
  }
}

in child functional component.

const AudioTrack = (props) => {
  useEffect(() => {});
  return(  
    <GridContainer>
    <PlayButton onClick={this.handlePlay} />
    <div id=track0 ></div>
    </GridContainer>
  );
}

It seems there is no object this.track_0Ref.current in parent class...

Where should I wrong??

Upvotes: 1

Views: 388

Answers (1)

Arman Charan
Arman Charan

Reputation: 5797

AudioTrack needs to forward the ref it was provided via props.ref to an actual DOM element.

e.g.

<div id="track0" ref={props.ref}/>

Upvotes: 1

Related Questions