Passing parent component to child in ReactJS

I like to send attribute / property / state properties from a child component to the parent component when the onDrag event onDrag . I could not find the correct documentation on this.

Here is my code:

 /*** @jsx React.DOM */ var APP=React.createClass({ getInitialState:function() { return {url:'http://www.youtube.com/embed/XGSy3_Czz8k'} }, handleDrag:function(vidurl) { alert(vidurl); //i need to get child component url here. }, render:function(){ return <div> <VideoFrame src={this.state.url} /> <hr/> <videos handle={this.handleDrag(vidurl)} /> </div> } }); var VideoFrame=React.createClass({ render:function(){ return <div> <iframe width="420" height="315" src={this.props.src}> </iframe> </div> } }); var videos=React.createClass({ getInitialState:function() { return {vidurl:'http://www.youtube.com/embed/XGSy3_Czz8k'} }, render:function() { return <img src="http://upload.wikimedia.org/wikipedia/en/a/a6/Size_Small.PNG" onDrag={this.props.handle.bind(this.state.vidurl)}></img> //trying to send state value from here } }); React.renderComponent(<APP />, document.body); 

I hope my code becomes clear.

+7
javascript reactjs react-jsx reactjs-native
source share
2 answers

In the App component of this line

 <videos handle={this.handleDrag(vidurl)} /> 

incorrectly, you need to pass a callback function instead of a function call.

In VideoForm, this line

 return <img src="http://upload.wikimedia.org/wikipedia/en/a/a6/Size_Small.PNG" onDrag={this.props.handle.bind(this.state.vidurl)}></img> //trying to send state value from here 

wrong, this.props.handle is the parent callback, you just need to call this.props.handle (this.state.videoUrl)

Correct implementation:

 var APP = React.createClass({ getInitialState:function() { return {url:'http://www.youtube.com/embed/XGSy3_Czz8k'} }, // Parent callback, pass this function to the child component handleDrag:function(videoUrl) { alert(videoUrl); }, render: function() { return ( <div> <Videos handle={this.handleDrag} /> </div> ); }) var Videos = React.createClass({ getInitialState:function() { return {vidurl:'http://www.youtube.com/embed/XGSy3_Czz8k'} }, handleChanged: function(event) { if(this.props.handle) { this.props.handle(this.state.videoUrl); } }, render:function() { return <img src="http://upload.wikimedia.org/wikipedia/en/a/a6/Size_Small.PNG" onDrag={this.handleChanged}></img> //trying to send state value from here } }); 
+12
source share

The first argument to bind is the object that is set to "this" when calling the bound method, the second argument to bind is the first argument passed to.

Do not forget to also pass functions, in the first class you call handleDrag, and then pass the return value to the video component, and not pass handleDrag itself.

+1
source share

All Articles