0

I'm trying to display react component based on what the pair name is, but I am not sure how to get that to happen. This is the code I have so far, any suggestions?

class App extends React.Component {
  state = {
    bases: ['EUR', 'AUD', 'CAD', 'JPY', 'NZD'],
    selectedBase: 'USD',
  };

  displayGraph = () => {
    if(document.getElementById('pairName').innerText === 'USD/EUR'){
      <Graph defaultBase={"EUR"} />
    } else if (document.getElementById('pairName').innerText === 'USD/CAD'){
      <Graph defaultBase={"CAD"} />  
    } else if(document.getElementById('pairName').innerText === 'USD/AUD'){
      <Graph defaultBase={"NZD"}/>
    } else if(document.getElementById('pairName').innerText === 'USD/NZD'){
      <Graph defaultBase={"AUD"}/>
    } else if (document.getElementById('pairName').innerText === 'USD/JPY') {
      <Graph defaultBase={"JPY"}/>
    }
  }

  render(){
    return (
        <div id="three">
        <h2 id="pairName">USD/EUR</h2>

          {/* GOAL: show graphs when correct pairs are selected */} 

          {this.displayGraph}

        </div>
  }
}

export default App;
1
  • This would be way simpler with a look-up table like { "USD/EUR": { ... } }. Commented Nov 14, 2020 at 23:26

1 Answer 1

4

In your code I think you are missing return before the <Graph... />.

However another way you could do this could also be like this:

class App extends React.Component {
  state = {
    bases: ['EUR', 'AUD', 'CAD', 'JPY', 'NZD'],
    selectedBase: 'USD',
  };

  displayGraph = () => {
    switch(document.getElementById('pairName').innerText) {
    case 'USD/EUR':
        return <Graph defaultBase={"EUR"} />;
    case 'USD/CAD':
        return <Graph defaultBase={"CAD"} />;
    case 'USD/AUD':
        return <Graph defaultBase={"NZD"}/>;
    case 'USD/NZD':
        return <Graph defaultBase={"AUD"}/>;
    case 'USD/JPY':
        return <Graph defaultBase={"JPY"}/>;
  }

  render(){
    return (
        <div id="three">
        <h2 id="pairName">USD/EUR</h2>
          {this.displayGraph}
        </div>
  }
}

export default App;

P.s. As a side note, I would look at converting the React class to a function and using the useState hook as it is the newer way of writing react code. You can read more about it here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.