Reputation: 67
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;
Upvotes: 0
Views: 74
Reputation: 1299
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.
Upvotes: 4