1

I have an array of objects I wanted to display in a table. I have the following code

class Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: this.props.data
    };
  }

  render() {
    return (
      <table>
          {this.state.data.map(row => {
            console.log(row);
            <Test/>
          })}
      </table>
    );
  }
}

class Test extends React.Component {
  constructor(props) {
    super(props);
    console.log("7");
  }

  render() {
    return;
  }
}

The console.log() in the Table prints out all my data correctly, however, the console.log() in my Test constructor never prints.
Why is the Test not being created?


My proper rows is below:

class Rows extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: this.props.rowData
    };

    console.log("2");
  }

  render() {
    return (
      <tr>
        <td>{this.state.data.paymentFrom}</td>
        <td>{this.state.data.paymentTo}</td>
        <td>{this.state.data.paymentPeriod}</td>
        <td>{this.state.data.paymentAmount}</td>
      </tr>
    );
  }
}

2 Answers 2

2

For the Test component to be rendered correctly, you must to return the component, if it never return on the function body, will never gonna print.

Try this way:

class Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: this.props.data
    };
  }

  render() {
    return (
      <table>
          {this.state.data.map(row => {
            console.log(row);

            return (<Test/>)
          })}
      </table>
    );
  }
}

class Test extends React.Component {
  constructor(props) {
    super(props);
    console.log("7");
  }

  render() {
    return;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to return <Test/> for it to initiate and render.

4 Comments

Doesn't seem to work, that whole section is inside a return already.
This answer is correct, but if you aren't seeing logging, then you aren't passing data to your Table as props. You don't show us that code.
you are correct, I was testing the wrong version. Why is an extra return needed?
The extra return is not for React but for the .map method. That's how .map works in js. You have to return from with .map() method. If you don't, it won't be part of the new array constructed by .map.

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.