Nesting React Components via a Function?

I’d like to have a function displayStarRating(starRating) that displays the number of stars an item has received. This works:

import React from 'react';`

function displayStarRating(starRating) {
  var result = [];
  for (var i = 1; i <= starRating; i++) {
    result.push(<div>===STAR===</div>);
  }
  return result;
}

class Reviews extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
        <div>
                {displayStarRating(4)}
        </div>
    );
  }
}

export default Reviews;

But what if I want to use a component (e.g. a Material-ui component) for each star? This doesn’t yet work:

import React from 'react';`
import Star from 'material-ui/svg-icons/toggle/star';

function displayStarRating(starRating){
  var result = [];
  for (var i = 1; i <= starRating; i++){
    result.push(<Star  />);
  }
}


class Reviews extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
        <div>
                {displayStarRating(4)}
        </div>
    );
  }
}

export default Reviews;

…the stars do not appear in the resulting html source or in the client browser.

Is it possible to nest components via a function call?

My mistake. It does work!

1 Like