Search code examples
javascriptarraysreactjsmap-function

JSX not returning map function with React


I have worked on this problem for quite some time and I am at a lost on how to continue forward. I am trying to return a description of a stock when a certain symbol is entered into the input field. The console.log returns the value of the description when a symbols are entered but it doesn't render it to the page. I have tried to return the whole statement including the map function but that just cancels out my other return statement. I don't know what else to do. Can someone point me in the right direction?

Here is my code:

render() {
        const { stockSymbol, userInput } = this.state




        stockSymbol.map((stock, i) => {

            if (userInput === stock.symbol) {

                return <h2 className="symboldescription" key={i}>
                    {stock.description}
                </h2>,

                    console.log(stock.description + " match")

            }
        })

        return (
            <div className="enterstock">
                <h1 className="title">Enter Stock Symbol</h1>
                <span className="symbol">{this.state.userInput}</span>
                <form className="inputfields" onSubmit={this.getSymbol}>
                    <input type="text" className="symfields" name="symbolname" onChange={this.typeSymbol}></input>
                    <button type="submit" className="btn">Send</button>
                </form>
            </div >
        )

    }
}

Solution

  • You should be including it as part of the return statement for the render method. For example,

    render() {
      const { stockSymbol, userInput } = this.state;
    
      return (
        <div className="enterstock">
          <h1 className="title">Enter Stock Symbol</h1>
          <span className="symbol">{this.state.userInput}</span>
          <form className="inputfields" onSubmit={this.getSymbol}>
            <input type="text" className="symfields" name="symbolname" onChange={this.typeSymbol}></input>
            <button type="submit" className="btn">Send</button>
          </form>
          {stockSymbol.map((stock, i) => {
            if (userInput === stock.symbol) {
              return <h2 className="symboldescription" key={i}>
                {stock.description}
              </h2>
            }
          })}
        </div>
      )
    }