React JSX

황희윤·2021년 11월 27일
0

JSX

  • JSX looks similar to HTML, but it's not. It's a syntex extension to JavaScript.

  • JSX produces React "elements".

  • React JSX doesn't put markup and logic in seperate files. It combines them to one unit called "component".

  • Component contains both markup and logic.

  • Using JSX is not essential, but helpful when working with UI inside the JavaScript code.


How to use JSX

  • It's available to write JavaScript code in curly braces

  • React show many useful errors and warning messages.

  • Because JSX is one of JavaScript expressions, if statements and for loop can be written in JSX.

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

const person = {
  firstName: 'Harper',
  lastName: 'Perez'
};

function sayHello(person){
	if(person){
    return <h1>Hello, {personName(person)}!<h1>
    }
    return <h1>Hello, Stranger.</h1>;
}
  • Quotes can be used to specify string literals as attributes.
const element = <div tabIndex="0"></div>;
  • Curly braces are also used to embed a JavaScript expression in an attribute. But using quotes around the curly braces are not allowed.
const element = <img src={user.avatarUrl}></img>;
  • JSX is closer to JavaScript than to HTML. So React DOM uses camelCase to name the variable.

  • Even thoguh it looks similar to JavaScript, but it's different with JavaScript. So it's not allowed to use same keyword with JavaScript.

  • JSX can express Object. Babel compiles JSX down to React.createElement() calls.
    These two examples are same.

const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);
const element = React.createElement(
  'h1',
  {className : 'greeting'},
  'Hello, world!'
 );
  • With these codes, the object called "React element" is created. React reads the object like this and uses it to construct the DOM.
const element = {
  type: 'h1',
  props: {
    className: 'greeting',
    children: 'Hello, world!'
  }
};

Advantage of JSX

  • JSX prevents injection attacks like XSS(cross-site-scripting) attacks.

  • React DOM escapes any values in JSX before rendering them. Escape means change the characters to the new strings. Because it change the characters to the new strings, the injection attack code may be written down in program but it can't be worked properly cause it's written down with the new strings.

  • It is safe to embed user input in JSX.

profile
HeeYun's programming study

0개의 댓글