Google News
logo
CoffeeScript - Interview Questions
What is JSX in CoffeeScript?
JSX is JavaScript containing interspersed XML elements. While conceived for React, it is not specific to any particular library or framework.
 
CoffeeScript supports interspersed XML elements, without the need for separate plugins or special settings. The XML elements will be compiled as such, outputting JSX that could be parsed like any normal JSX file, for example by Babel with the React JSX transform. CoffeeScript does not output React.createElement calls or any code specific to React or any other framework. It is up to you to attach another step in your build chain to convert this JSX to whatever function calls you wish the XML elements to compile to.
 
Just like in JSX and HTML, denote XML tags using < and >. You can interpolate CoffeeScript code inside a tag using { and }. To avoid compiler errors, when using < and > to mean “less than” or “greater than,” you should wrap the operators in spaces to distinguish them from XML tags. So i < len, not i<len. The compiler tries to be forgiving when it can be sure what you intend, but always putting spaces around the “less than” and “greater than” operators will remove ambiguity.
renderStarRating = ({ rating, maxStars }) ->
  <aside title={"Rating: #{rating} of #{maxStars} stars"}>
    {for wholeStar in [0...Math.floor(rating)]
      <Star className="wholeStar" key={wholeStar} />}
    {if rating % 1 isnt 0
      <Star className="halfStar" />}
    {for emptyStar in [Math.ceil(rating)...maxStars]
      <Star className="emptyStar" key={emptyStar} />}
  </aside>
​
var renderStarRating;
​
renderStarRating = function({rating, maxStars}) {
  var emptyStar, wholeStar;
  return <aside title={`Rating: ${rating} of ${maxStars} stars`}>
    {(function() {
    var i, ref, results;
    results = [];
    for (wholeStar = i = 0, ref = Math.floor(rating); (0 <= ref ? i < ref : i > ref); wholeStar = 0 <= ref ? ++i : --i) {
      results.push(<Star className="wholeStar" key={wholeStar} />);
    }
    return results;
  })()}
    {rating % 1 !== 0 ? <Star className="halfStar" /> : void 0}
    {(function() {
    var i, ref, ref1, results;
    results = [];
    for (emptyStar = i = ref = Math.ceil(rating), ref1 = maxStars; (ref <= ref1 ? i < ref1 : i > ref1); emptyStar = ref <= ref1 ? ++i : --i) {
      results.push(<Star className="emptyStar" key={emptyStar} />);
    }
    return results;
  })()}
  </aside>;
};
Older plugins or forks of CoffeeScript supported JSX syntax and referred to it as CSX or CJSX. They also often used a .cjsx file extension, but this is no longer necessary; regular .coffee will do.
Advertisement