Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS rendering components based on user select

So I'm basically a week old to react and have not written any javascript code for years. So please forgive my ignorance if any.

Question I have created three different component classes

 const CreatedDate = React.createClass({
  displayName: 'CreatedDate',
  propTypes: {
    name: 'CreateDate',
    from: React.PropTypes.string,
    to: React.PropTypes.string,
    format: React.PropTypes.string,
    onChange: React.PropTypes.func
  },

//rest of the code and functions

And likewise, I have a class similar to this called ClientSignedDate and VerificationDate all of which containing basically same input props but get data from different columns of the same table.

In a separate ParentClass called Filter I have created an array of these components inside this class

const dateOptions = [CreatedDate,ClientSignedDate,VerificationDate];

It was previously working when there was only one component

          <CreatedDate
            from={this.props.filter.createdDateFrom}
            to={this.props.filter.createdDateTo}
            onChange={this.handleCreatedDateChange}
          />

And I basically want to render the component based on user selection but I'm not able to figure out how to do so. Something similar to the snippet below but which allows rendering.

 <select>{dateOptions.map(x => <option>{x}</option>)}</select>
like image 429
shashwatZing Avatar asked Mar 08 '26 12:03

shashwatZing


1 Answers

And I basically want to render the component based on user selection

The simplest way is

{ this.state.selection === 1 && <CreatedDate ... /> }
{ this.state.selection === 2 && <ClientSignedDate ... /> }

And so on.

Edit: based on additional info, another option is:

const dateOptions = [CreatedDate, ClientSignedDate, VerificationDate];
const Comp = dateOptions[this.state.selection];  // pick element

then use

<Comp 
    from={this.props.filter.createdDateFrom}
    to={this.props.filter.createdDateTo}
    onChange={this.handleCreatedDateChange}
/>

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!