Instagram
youtube
Facebook
Twitter

JSX

React JSX

  • JSX, is a syntax extension to javascript. React recommends it for creating UI's.
  • It is not necessary to use JSX, but it is more useful as it shows more errors and warnings.

Embedding expression in JSX

  • In the example below, we have declared a variable name and then used it as JSX by wrapping it inside curly braces.
const name = 'Codersdaily';
const element = <h1>Hello, {name}</h1>;
  • You can put any kind of JS expressions inside curly braces in JSX.

For eg, 

function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'Mradul',
  lastName: 'Mishra'
};

const element = (
  <h1>
    Hello, {formatName(user)}!
  </h1>
);
  • In the example above we have called a function  formatName(user).
  • We have also utilized sum functionality to concatenate the firstName and lastName.

 

Specifying Attributes with JSX.

  • We can use curly braces to embed a JS expression in an attribute.
const element = <img src={user.imgUrl}></img>;

 

JSX Prevents Injection Attacks

  • In react jsx everything is converted to a string before it is rendered. This prevents XSS(cross-site-scripting) attacks.