0

I have a state value in React that changes on user input. Based on that state value, I want to access a different key of an object I'm receiving in props.

I want to be able to access this.props.data.bpi.USD, this.props.data.bpi.GBP, or this.props.data.bpi.EUR based on the user's selection, and then get various elements from that object.

I tried achieving this with string interpolation, but it didn't work. I've also looked at various SO suggestions but sadly none were applicable.

I want to be able to do something like: this.props.data.bpi.${this.state.currency}

Any ideas? Here's the code so far (as you can see, I'm currently hardcoding the currency):

class Prices extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currency: "USD",
    };
  }

  render() {
    return (
      <div>
        <ul className="list-group">
          <li className="list-group-item">
            Bitcoin rate for {this.props.data.bpi.USD.description}:{" "}
            <span className="badge badge-primary">
              {this.props.data.bpi.USD.code}
            </span>{" "}
            <strong>{this.props.data.bpi.USD.rate}</strong>
          </li>
        </ul>
        <select
          className="form-control"
          onChange={(e) => {
            this.setState({ currency: e.target.value });
          }}
        >
          <option value="USD">USD</option>
          <option value="GBP">GBP</option>
          <option value="EUR">EUR</option>
        </select>
      </div>
    );
  }
}

export default Prices;
crevulus
  • 1,658
  • 12
  • 42

0 Answers0