score:2

Accepted answer

if your components are really similar,you can create one single component which does some actions and renders some result based on props.

just pass some props. and inside of your component, do your actions like you do in those 3 component separately. here, i tried to demonstrate how to use props to render different results from same component:

class mixedcomponent extends react.component {
  constructor(props) { 
    super(props)
    this.state = {type: ''}
  }

  componentdidmount() {
    if (this.props.prop1) // if prop1 exists
      this.setstate({type: 'do something'})
    else 
      this.setstate({type: 'something else'})
  }

  render() {
    let result;
    if (this.props.prop1) {
      result = (
        <div>
          render this component based on <strong>{this.props.prop1}</strong>
          <p>type -> {this.state.type}</p>
        </div>
      )
    } else if (this.props.prop2) {
      result = (
        <div>
          render this component based on <strong>{this.props.prop2}</strong>
          <p>type -> {this.state.type}</p>
        </div>
      )
    }
    else if (this.props.prop3) {
      result = (
        <div>
          render this component based on <strong>{this.props.prop3}</strong>
          <p>type -> {this.state.type}</p>
        </div>
      )
    }
    return result
  }
}

and use this component with different props in your main component:

class main extends react.component {
  render() {
    return (
      <div>
        <h4>render different results based on props with same component!</h4>
        <hr/>
        <mixedcomponent prop1="hello,"/>
        <mixedcomponent prop2="dear"/>
        <mixedcomponent prop3="world!"/>
      </div>
     )
  }
}

this is just a demonstration of using props. you can derive the idea from here. here is a working example on codepen:

https://codepen.io/anon/pen/dreqzk?editors=1010

you can play with it.


Related Query

More Query from same tag