Edgars Šusts
Edgars Šusts

Reputation: 111

Get react states name using props

I'm wondering if it is possible to get state name using this.props. Example:

this.state.(this.props.name)

I am setting state like this:

  onInputChange = (e) => {
   this.setState({[e.target.name]: [value: e.target.value, error: this.props.error]})
  }

And e.target.name come from <input name={this.props.name} />.

I need somehow to display those states from array.

Full code below. I will add input validation there later after i figure out this step.

import React, {Component} from 'react';

class Input extends React.Component {
 constructor(props){
  super(props);
  this.state = {

  }
 }
 onInputChange = (e) => {
  this.setState({[e.target.name]: [value: e.target.value, error: this.props.error]})
 }
 render () {
  return(
   <div className="form-group">
    <span>HERE WILL GO ERROR FROM STATE ARRAY AFTER VALIDATION</span>
    <input
     onChange={this.onInputChange}
     type={this.props.type}
     name={this.props.name}
     className="form-control input-lg"
     placeholder={this.props.placeholder}
    />
  </div>
  )
 }
}

export default Input;

Thanks.

Upvotes: 0

Views: 2026

Answers (1)

Sawan Patodia
Sawan Patodia

Reputation: 839

You can use this.state[this.props.name].

I have created working code in sandbox. Please have a look at https://codesandbox.io/s/pp3o0r2zrq

Upvotes: 3

Related Questions