Reputation: 622
In a quick summary what I have implemented is a photoupload system. I have a div that displays the preview of the image uploaded. This div lies in the parent component we will call parent.jsx. Inside the child component we call child.jsx I have implemented an upload system.
Inside child.jsx I have the following code:
const FileUpload = React.createClass({
render: function() {
return(
<div>
//dropzone is essentially a file input element
<Dropzone multiple={false} onDrop={this._onDrop}>
</Dropzone>
</div>
);
},
_onDrop: function(files) {
this.setState({
photo: files
});
},
I want to pass the photo
object into my parent file and display it in the following div with this conditional:
<div>
{this.state.coverPhoto.map(function(file) {return <img key={1} src={file.preview} />;})}
</div>
I was thinking about creating a function that returns the photo object when called upon in the child component. maybe something like this within the child component:
returnFiles: function() {
return Photo
}
Then in the parent component I can call FileUpload.returnFiles and set my state with whats returned. Any ideas?
Upvotes: 1
Views: 1375
Reputation: 20634
While I believe it makes intuitive sense to call a child component's function, this breaks one of the fundamental reasons why React is such a great tool.
React greatly reduces the complexity of an application by restricting the flow of data from parent to child.
However, just like any other piece of data in JavaScript, you can pass down functions to children. This way they are only called in the child's scope, but handled where you need them.
const Parent = React.createClass({
render: function() {
return(
<Child onDrop={this.handleOnDrop}
);
},
handleOnDrop: function(files) {
this.setState({
photo: files
});
}
}
const Child = React.createClass({
render: function() {
<Dropzone multiple={false} onDrop={this.props.onDrop} />
}
})
Upvotes: 1