0

For my website I want to include a feature that helps users randomly click a link programatically. The event happens in the parent component called StreamingPlaza, and its has a list of children components called StreamingCard, each containing a streaming link. Below is my code:

Streaming Plaza

class StreamingPlaza extends Component {

  state = {
    ......
    }

    roomclicks = React.createRef([]);

    componentDidMount() {
      this.roomclicks.current[0].handleClick();
   }

     renderRoom = (room) => {
        return <StreamingCard info={room} ref={(ref) => {this.roomclicks.current[0] = ref}}></StreamingCard>;

     render() {

       const rooms = this.props.rooms;

       return (
        { rooms && rooms.map (room => {
          return this.renderRoom(room);  
        })
      }
    );
}
}

Streaming Card

class StreamingCard extends Component {

  constructor(props){
    super(props);
    this.state = {
     ......
    }

  handleClick = () => {
    console.log("called");
    document.getElementById("link").click();
  }

  render() {
    return (
       ✔️ Streaming Link: <a id="link" href=......></a>
    );
  }
 }

I got the error "this.roomclicks.current[0].handleClick is not a function." I looked through many relevant stackoverflow posts, and the answers suggested that this code was supposed to work. I would appreciate a lot if someone can tell me where I get it wrong. Thanks!

Xi Liu
  • 559
  • 9
  • 18
  • Thanks for the reply! A constructor is needed to use "this." I tried this approach and it did not work. – Xi Liu Jun 16 '20 at 22:32
  • Check out this other question, its very similar and has some great answers: [Call child method from parent](https://stackoverflow.com/questions/37949981/call-child-method-from-parent) – Seth Lutske Jun 16 '20 at 23:58
  • Thanks for the reply! I'm using the "Using class components >= react@16.4" part of the most-upvoted answer. – Xi Liu Jun 17 '20 at 00:49
  • what does your `this.roomClicks.current` look like? Is it an array? I feel like it should be `this.roomClicks[0].current` ... `.current` is not usually an array. – Seth Lutske Jun 17 '20 at 01:01
  • console.log(this.roomclicks.current[0]) indeed printed out the expected result. – Xi Liu Jun 17 '20 at 04:41
  • what did it print out – Seth Lutske Jun 17 '20 at 04:50

0 Answers0