Unable to render class method in the App component ( No error)

When returning JSX in a class component as you can see below I am calling a class method test. That method runs and I see output in the console. However it does not render to the screen. (I have checked the dev console for html changes) I am failing to understand why it does not render.

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {

  test = () => {
    console.log('I returning div');
    return <div>hello</div>;
  };

  render() {
    return (
      <div className="App">
        <div>
          <button onClick={this.test}>Click ME!</button>
        </div>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("container"));

To workaround this I can instead I pass in another component in the return for render and that will work as expected. But what if I want to return this.state of App then I need a method that returns jsx with the App state as a method of App.

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <div>
          <Test />
        </div>
      </div>
    );
  }
}

function Test() {
  return <div>Hello</div>;
}
ReactDOM.render(<App />, document.getElementById("container"));

Your class method is running and returning a value in the first example, but nothing in your code is doing anything with the returned value. In your render() method’s JSX, you could include {this.test()} to have it render the returned value to prove it is working.

I’m not quite understanding what you’re hoping to do. Can you describe it a little more?

1 Like

Hey @selectall

TLDR; I just simply switched the built in array map with the help of the React Docs[2] and resolved the issue.

Yup you’re right I needed to include this.test() in the example. I made that in react playground really quick and didn’t test it. I really appreciate your help. It set me on the right path to understanding what my issue was.

In essence I was using a forEach function in my personal project like so:

    return this.state.tasks.forEach(item => {
      console.log(item);
      return <li key={item.id}>{item.TaskName}</li>
    })

As you know the forEach function doesn’t return anything even if it does the value is discarded[1]. I made a mistake in two places first assuming that I can run the return on each item and that the final forEach returned value won’t matter, second that JSX render can’t take in an array of JSX object values and resolve them to individual HTML elements. I am new to JS and React it was my mistake.

Thanks a lot for helping me out.

References:
[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
[2] https://reactjs.org/docs/lists-and-keys.html