THpubs
THpubs

Reputation: 8172

When and where to separate a React component into a separate file? When to do it in the same file?

Now let's say we have to output a select field in a form. Have to set the select options based on the data passed into the component.

When using es6 classes, we can use a method in the same file to display it like this :

selectForm() {
  <input ....>
  this.props.data.map((data) => {
    option...
  })
}

render() {
  return (
    <div>
       {this.selectForm()}
    </div>
  )
}

We can also add this into a separate file, import it as a separate component and use it in this file like this :

render() {
  return (
    <div>
       <SelectField data={this.props.data}>
    </div>
  )
}

Out of the two options, what is the recommended way of doing things?

Upvotes: 0

Views: 3214

Answers (1)

Nishanth Matha
Nishanth Matha

Reputation: 6081

If you want to reuse the component (in select case you surely would) then write it in a separate file and import it. If it's just a app specific component do it in the app component itself (method 1 in your example). Read more about reusable components here: https://facebook.github.io/react/docs/reusable-components.html

Upvotes: 2

Related Questions