concept JSX in category react

appears as: JSX, JSX
React Hooks in Action

This is an excerpt from Manning's book React Hooks in Action.

Wait! What now? Is that HTML? XML? JavaScript? Well, programming with React is programming in JavaScript. But, React provides an HTML-like syntax for describing your UI called JSX. Before running your app, the JSX needs to be preprocessed to convert it into the actual JavaScript that creates the elements of your user interface. At first it seems a bit strange, mixing HTML with your JavaScript, but it turns out the convenience is a big plus. And once your code finally runs in the browser (or other environment) it really is just JavaScript. A package called Babel is almost always used to compile the code you write into the code that will run. You can find out more about Babel at bablejs.io.

This chapter only offers a high-level overview of React, so we won’t explore JSX any further here. It’s worth mentioning up front though because it’s a widely used part of React development. In fact, in my opinion, React’s JavaScriptiness is one of its appeals - although other opinions are available - and, for the most part, it doesn’t introduce many constraints. While best practices have emerged and continue to do so, being a good JavaScript programmer and being a good React programmer are very similar skills.

  • Use the special ref attribute in the JSX to ask React to automatically assign a reference to the button element to nextButtonRef.current.
  • Isomorphic Web Applications: Universal Development with React

    This is an excerpt from Manning's book Isomorphic Web Applications: Universal Development with React.

  • Because the server will render components, you’ll need to run JSX on the server— JSX is the template language that React uses to declare the view. Node.js doesn’t understand how to run JSX, so you’ll need to compile the JSX into JavaScript before using it on the server. I discuss JSX later in the chapter.
  • Listing 2.3. Webpack configuration—webpack.config.js
    module.exports = { entry: "./src/main.jsx", #1 output: { path: __dirname + '/src/', #2 filename: "browser.js" #3 }, module: { rules: [ { test: /\.(jsx|es6)$/, #4 exclude: /node_modules/, #5 loader: "babel-loader" #6 }, ] }, resolve: { extensions: ['.js', '.jsx', '.css', '.es6'] #7 } }; #1 Defines input starting point or entry path—file runs only on browser #2 Output folder—the dist directory where we build all other files #3 Output filename #4 Regular expression that tells loader what files to apply loader to #5 Excludes node_modules because these files are already compiled and production ready #6 Defines loader to apply to matched files, for Babel to compile ES6 and JSX #7 Supported file extensions—empty file extension allows import statements with no extension (your src files have one extension but your compiled files have a different one) !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":1,\"ch\":63},{\"line\":1,\"ch\":65}],[{\"line\":20,\"ch\":0},{\"line\":20,\"ch\":2}],[{\"line\":3,\"ch\":63},{\"line\":3,\"ch\":65}],[{\"line\":21,\"ch\":0},{\"line\":21,\"ch\":2}],[{\"line\":4,\"ch\":63},{\"line\":4,\"ch\":65}],[{\"line\":22,\"ch\":0},{\"line\":22,\"ch\":2}],[{\"line\":9,\"ch\":63},{\"line\":9,\"ch\":65}],[{\"line\":23,\"ch\":0},{\"line\":23,\"ch\":2}],[{\"line\":10,\"ch\":63},{\"line\":10,\"ch\":65}],[{\"line\":24,\"ch\":0},{\"line\":24,\"ch\":2}],[{\"line\":11,\"ch\":63},{\"line\":11,\"ch\":65}],[{\"line\":25,\"ch\":0},{\"line\":25,\"ch\":2}],[{\"line\":16,\"ch\":63},{\"line\":16,\"ch\":65}],[{\"line\":26,\"ch\":0},{\"line\":26,\"ch\":2}]]"} !@%STYLE%@!

    2.3.2. Using JSX

    React uses a template language called JSX. For the most part, JSX looks and acts like normal HTML, which makes it easy to learn and use. JSX consists of HTML tags (which can also be additional React components) and sections of code that are JavaScript. The syntax is presented here:

    React in Action

    This is an excerpt from Manning's book React in Action.

    2.4.1. Creating components using JSX

    It’s important to master the fundamentals, but that doesn’t mean we have to make things difficult for ourselves. There are, it turns out, easier and better ways to create React components than only using React.createElement. Meet JSX: the better way.

    What is JSX? It’s an XML-like syntax extension to ECMAScript without any defined semantics, intended specifically for use by preprocessors. In other words, JSX is an extension of JavaScript that’s similar to XML and is only intended for use by code-transformation tools. It’s not something you’ll see incorporated into the ECMAScript specification at any point.

    JSX helps by allowing you to write XML-style (think HTML) code in place of using React.createClass. In other words, it lets you write code that looks like HTML but isn’t. A JSX preprocessor program like Babel—a transpiler that turns your JavaScript code into code that’s compatible with older browsers—will go through and convert all your JSX code to regular JavaScript like we’ve written so far. One implication is that running untransformed JSX code natively in the browser won’t work—you’ll get all sorts of syntax errors when your JavaScript is parsed.

    Writing XML-style, HTML-like code in your JavaScript might set your warning instincts off, but there are plenty of good reasons to use JSX, and I’ll cover them. For now, look at listing 2.11 to see what your comment box component might look like with JSX. I’ve omitted some code to make it easier to focus on the JSX syntax. Note that Babel is included as part of the environment on CodeSandbox. Normally, you’ll use a build tool like Webpack to transpile your JavaScript, but you can also import Babel and have it work without a build step. That’s much slower, though, and should never be done in production. You can learn more at https://babeljs.io.

    Listing 2.11. Rewriting components using JSX
    ... class CreateComment extends Component { constructor(props) { super(props); this.state = { content: '', user: '' }; this.handleUserChange = this.handleUserChange.bind(this); this.handleTextChange = this.handleTextChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } //... render() { return ( <form onSubmit={this.handleSubmit} className="createComment"> <input value={this.state.user} onChange={this.handleUserChange} #1 placeholder="Your name" #1 type="text" /> <input value={this.state.content} onChange={this.handleTextChange} placeholder="Thoughts?" type="text" /> <button type="submit">Post</button> </form> ); } } class CommentBox extends Component { //... render() { return ( <div className="commentBox"> <Post id={this.props.post.id} #2 content={this.props.post.content} #2 user={this.props.post.user} /> {this.state.comments.map(function(comment) { #3 return ( <Comment key={comment.id} content={comment.content} #3 user={comment.user} #3 /> ); })} <CreateComment onCommentSubmit={this.handleCommentSubmit} #4 /> </div> ); } } CommentBox.propTypes = { post: PropTypes.object, comments: PropTypes.arrayOf(PropTypes.object) }; ReactDOM.render( <CommentBox comments={data.comments} #5 post={data.post} />, node ); ...... #1 Instead of creating props on an object, in JSX you create them like you would in HTML—to pass in expressions, you use the {} syntax. #2 This is the Post React class you created before—note now it’s much clearer that it’s a custom component you created and looks like it would belong right at home in HTML. #3 Use regular JavaScript inside of {} to iterate over comments and create a comment component for each. #4 Pass in the handleComment-Submit handler as a property. #5 At the top level, CommentBox is also a custom component you give props to and pass to React DOM to render. !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":18,\"ch\":69},{\"line\":18,\"ch\":71}],[{\"line\":19,\"ch\":69},{\"line\":19,\"ch\":71}],[{\"line\":76,\"ch\":0},{\"line\":76,\"ch\":2}],[{\"line\":18,\"ch\":69},{\"line\":18,\"ch\":71}],[{\"line\":19,\"ch\":69},{\"line\":19,\"ch\":71}],[{\"line\":76,\"ch\":0},{\"line\":76,\"ch\":2}],[{\"line\":40,\"ch\":69},{\"line\":40,\"ch\":71}],[{\"line\":41,\"ch\":69},{\"line\":41,\"ch\":71}],[{\"line\":77,\"ch\":0},{\"line\":77,\"ch\":2}],[{\"line\":40,\"ch\":69},{\"line\":40,\"ch\":71}],[{\"line\":41,\"ch\":69},{\"line\":41,\"ch\":71}],[{\"line\":77,\"ch\":0},{\"line\":77,\"ch\":2}],[{\"line\":44,\"ch\":69},{\"line\":44,\"ch\":71}],[{\"line\":48,\"ch\":69},{\"line\":48,\"ch\":71}],[{\"line\":49,\"ch\":69},{\"line\":49,\"ch\":71}],[{\"line\":78,\"ch\":0},{\"line\":78,\"ch\":2}],[{\"line\":44,\"ch\":69},{\"line\":44,\"ch\":71}],[{\"line\":48,\"ch\":69},{\"line\":48,\"ch\":71}],[{\"line\":49,\"ch\":69},{\"line\":49,\"ch\":71}],[{\"line\":78,\"ch\":0},{\"line\":78,\"ch\":2}],[{\"line\":44,\"ch\":69},{\"line\":44,\"ch\":71}],[{\"line\":48,\"ch\":69},{\"line\":48,\"ch\":71}],[{\"line\":49,\"ch\":69},{\"line\":49,\"ch\":71}],[{\"line\":78,\"ch\":0},{\"line\":78,\"ch\":2}],[{\"line\":54,\"ch\":69},{\"line\":54,\"ch\":71}],[{\"line\":79,\"ch\":0},{\"line\":79,\"ch\":2}],[{\"line\":68,\"ch\":68},{\"line\":68,\"ch\":70}],[{\"line\":80,\"ch\":0},{\"line\":80,\"ch\":2}]]"} !@%STYLE%@!
    React Quickly: Painless web apps with React, JSX, Redux, and GraphQL

    This is an excerpt from Manning's book React Quickly: Painless web apps with React, JSX, Redux, and GraphQL.

    Then there’s JSX, which is probably the most frequent argument for not using React. If you’re familiar with Angular, then you’ve already had to write a lot of JavaScript in your template code. This is because in modern web development, plain HTML is too static and is hardly any use by itself. My advice: give React the benefit of the doubt, and give JSX a fair run.

    JSX is a little syntax for writing React objects in JavaScript using <> as in XML/HTML. React pairs nicely with JSX because developers can better implement and read the code. Think of JSX as a mini-language that’s compiled into native JavaScript. So, JSX isn’t run on the browser but is used as the source code for compilation. Here’s a compact snippet written in JSX:

    if (user.session)
      return <a href="/logout">Logout</a>
    else
      return <a href="/login">Login</a>

    Even if you load a JSX file in your browser with the runtime transformer library that compiles JSX into native JavaScript on the run, you still don’t run the JSX; you run JavaScript instead. In this sense, JSX is akin to CoffeeScript. You compile these languages into native JavaScript to get better syntax and features than that provided by regular JavaScript.

    I know that to some of you, it looks bizarre to have XML interspersed with JavaScript code. It took me a while to adjust, because I was expecting an avalanche of syntax error messages. And yes, using JSX is optional. For these two reasons, I’m not covering JSX until chapter 3; but trust me, it’s powerful once you get a handle on it.

    Were you able to tell that there are three elements, that they’re nested, and that the code uses a component from React Router? How readable is this code, compared to standard HTML? Do you think this code is eloquent? The React team agrees that reading (and typing, for that matter) a bunch of React.createElement() statements isn’t fun. JSX is the solution to this problem.

    Listing 3.2. Hello World in JSX
    ReactDOM.render( <h1>Hello world!</h1>, document.getElementById('content') )
    Listing 9.4. package.json for Menu in JSX