What is JSX ?

JSX is a preprocessor step that adds XML syntax to JavaScript. You can definitely use React without JSX but JSX makes React a lot more elegant.
Just like XML, JSX tags have a tag name, attributes, and children. If an attribute value is enclosed in quotes, the value is a string. Otherwise, wrap the value in braces and the value is the enclosed JavaScript expression.
·      JSX is faster because it performs optimization while compiling code to JavaScript.
·      It is also type-safe and most of the errors can be caught during compilation.
·      JSX makes it easier and faster to write templates if you are familiar with HTML.

JSX looks like regular HTML in most cases. Look at the code from App.jsx where we are returning div.

Even though it's similar to HTML, there are a couple of things you need to keep in mind when working with JSX.
import React from 'react'; class App extends React.Component { render() { return ( <div> Hello World!!! </div> ); } } export default App;



If you want to return more elements, you need to wrap it with one container element. Notice how we are using div as a wrapper for h1, h2 and pelements.

Nested Elements:

If you want to return more elements, you need to wrap it with one container element. Notice how we are using div as a wrapper for h1h2 and elements.

App.jsx
import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            <h1>Header</h1>
            <h2>Content</h2>
            <p>This is the content!!!</p>
         </div>
      );
   }
}
export default App;


JavaScript Expressions
JavaScript expressions can be used inside of JSX. You just need to wrap it with curly brackets {}. Example below will render 2.
import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            <h1>{1+1}</h1>
         </div>
      );
   }
}

export default App;
You can not use if else statements inside JSX but you can use conditional (ternary) expressions instead. In example below variable i equals to 1 so the browser will render true, if we change it to some other value it will render false.
import React from 'react';

class App extends React.Component {
   render() {

      var i = 1;

      return (
         <div>
            <h1>{i == 1 ? 'True!' : 'False'}</h1>
         </div>
      );
   }
}
 
export default App;

Styling 

React recommends using inline styles. When you want to set inline styles, you need to use camelCase syntax. React will also automatically append px after the number value on specific elements. You can see below how to add myStyle inline to h1 element.
import React from 'react';

class App extends React.Component {
   render() {

      var myStyle = {
         fontSize: 100,
         color: '#FF0000'
      }

      return (
         <div>
            <h1 style = {myStyle}>Header</h1>
         </div>
      );
   }
}
 
export default App; 

No comments:

Post a Comment