Ad

Using Refs Outside Component

- 1 answer

I have a ImageListComponent that contains an array of <ReactSwipe> elements. Each element have a unique id using ref={rid} and is slideable with two slides. The ImageListComponent is being used in another component called <CarFromImage> that includes methods to add and delete images to <ImageListComponent>.

The issue I am having is that inside the <ImageListComponent> I am able to programatically swipe an element with the method this.refs[rid].swipe.prev() but this is not possible if I want to use this method and reference to the spesific element in <CarFromImage>.

Some code in ImageListComponent.jsx:

             this.props.images.map(function(image, i){

                var rid = "ReactSwipe" + i; 

                return (<ReactSwipe ref={rid} key={i}>
                        <div>
                            <div>Something<div/>
                        </div>
                        <div>
                            <div style={styles.deleteIcon} onClick={this.props.deleteImage.bind(this, image, rid)}/>
                        </div>
                    </ReactSwipe>)
              }

Some code in CarFromImage.jsx:

    render: function () {
         return <ImageListComponent carImages={this.state.car.images} addImage={this.addImage} deleteImage={this.deleteImage}/>  

And the method as I want to use it in CarFromImage.jsx:

    deleteImage: function(selectedImage, rid){
        this.getFlux().actions.car.deleteImageFromCar(selectedImage);        
        this.refs[rid].swipe.prev();
    }

Have anyone used a ref outside its component before and know how I can attack this issue or do have some other suggestion? If nothing else I could just throw everything inside one big .jsx-file, but I would like to be able to split my project into smaller components. Any help would be much appreciated!

Ad

Answer

If you assign a ref to your parent node.

Like:

render: function () {
     return <ImageListComponent carImages={this.state.car.images} addImage={this.addImage} deleteImage={this.deleteImage} ref="parent" />
}

Can you not get the child refs like:

deleteImage: function(selectedImage, rid){
    this.getFlux().actions.car.deleteImageFromCar(selectedImage);        
    this.refs.parent.refs[rid].swipe.prev();
}

Demo: http://jsbin.com/yixujofixi/1/edit?js,output

Ad
source: stackoverflow.com
Ad