Search code examples
javascriptreactjsuser-interfacerecharts

React Conditional Renderings with states


I have two select options, and i have to display the two teams data in the charts when i select the two teams: Home Team and Away Team

This is the prototype done with codepen

At the moment i can only display in the chart one Line Component with dataKey and not the 2 Lines components for the two teams when i select both in the dropdowns.

How can i say in React when i select the Team Home in the first Select display the hometeam Line Component with the datakey state value.

{this.state.hometeam && <Line type='monotone' key={'1'} dataKey={this.state.value} stroke='#132908' yAxisId={1} activeDot={{fill: '#132908', stroke: 'none', r: 6}}/>}

Same for the awayteam in the other select

{this.state.awayteam && <Line type='monotone' key={'1'} dataKey={this.state.value} stroke='#132908' yAxisId={1} activeDot={{fill: '#132908', stroke: 'none', r: 6}}/>}

In the demo i have only displayed the generic Line Component not depending on the state


Solution

  • Your graph is driven off of this single this.state.value which is overwritten when either dropdown is selected. I would split that up into two separate properties in the state.

    state = {
      data: initialState
      hometeamValue: '',
      awayteamValue: ''
    }
    
    handleChangeHomeTeam = (e) => {
      this.setState({
        hometeamValue: e.target.value,
      });
    };
    
    handleChangeAwayTeam = (e) => {
      this.setState({
        awayteamValue: e.target.value,
      });
    };
    
    render(){
      return(
        // ...
        <select value={this.state.hometeamValue} onChange={this.handleChangeHomeTeam}>
          <option value="Betis">Betis</option>
          <option value="Real">Real</option>
        </select>
        <select value={this.state.awayteamValue} onChange={this.handleChangeAwayTeam}>
          <option value="Betis">Betis</option>
          <option value="Real">Real</option>
        </select>
        // ...
        <Line dataKey={this.state.hometeamValue} ... />}
        <Line dataKey={this.state.awayteamValue} .../>}
      }
    }