React component can't take ref

I'm trying to give the components I render on an array.map a reference so later on I can call some of the functions inside those components.

There would be 3 instances of the same component, and I'm getting this error when give them a ref:

Uncaught Error: Stateless function components cannot have refs.

Here, the render method of the parent component that is trying to render those 3 children components:

render() {
const { strings } = this.props;

const ElementsContainer = ({elements}) => (
  <div className="containerSection">
    {elements.map( (element, i) => {
      return(<div key={"container"+i} className="camaraLentaContainer" id={"camaraLentaContainer" + i}>

        <CamaraLenta ref={"camaraLenta"+i} index={i} images={element.camaraLenta.images}/>

      </div>)
      })
    }
  </div>
)

return (
  <div className="home" >

    <ElementsContainer elements={strings.elements} />

  </div>
);

}

Here, the CamaraLenta (child) component, very simplified so we can see..

import ...;

export default class CamaraLenta extends React.Component {
  static propTypes = {
    name: PropTypes.string,
  };

  static contextTypes = {
    baseUrl: PropTypes.string.isRequired,
    project: PropTypes.string.isRequired
  }

  constructor(props) {
    super(props);

    this.state = {
        slideIndex: 0,
        loading: false,
        imagesTotalDataSrc: [],
        imagesTotalDataLoaded: 0,
        timeoutSlider: null
    };

    this.handleSliderClick = this.handleSliderClick.bind(this);
  }

  componentDidMount() {

  }

    //Touch/Click slider, we kill timeout
    handleSliderClick() {
        clearTimeout(this.state.timeoutSlider);
    }

    registerEvents(){
        $("html, body").on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function(){
        $("html, body").stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup'); 
      });
    }

  render() {
    const {index} = this.props;

    return (
      <div>

        <div className="slidesContainer"> 
            <canvas id={"stage" + index}>
                Tu navegador no soporta canvas
            </canvas>
            <div className="slider" id={"slider" + index} onClick={this.handleSliderClick}></div>

            <Loading visible={this.state.loading}/>
        </div>

      </div>
    );
  }
}`

My versions:

"react": "^15.5.4",
"react-redux": "^5.0.5",
"redux": "^3.7.0",

1 answer

  • answered 2017-06-17 18:06 Yuri Ramos

    Stateless component don't work with refs, if you really want to uncapsulate your component using the findDOMNode, convert your component to a class based component or downgrade your react to any version before 0.14 (not recommended).

    More info in this page, the discussion about why they removed this feature from stateless components https://github.com/facebook/react/issues/4936