React

How to use JSX

jsx

JSX – JSX stands for Javascript XML and is preferred way of writing React elements/code. Below is a very simple example.

const element = <h1>Hello, Ojb Labs!</h1>;

Embedding expressions in JSX

const name = 'Ojb Labs';
const element = <h1>Hello, {name}</h1>;

ReactDOM.render(
  element,
  document.getElementById('root')
);

You can put any javascript expression inside curly brackets {} in JSX. For example, 3 + 7book.name, or getBookDetails(book) are all valid JavaScript expressions.

In the example below, we embed the result of calling a JavaScript function, getBookDetails(book), into an <h1> element.

function getBookDetails(book) {
  return book.name + ' ' + book.author;
}

const book = {
  name: 'The Lord of the Rings',
  author: 'J.R.R. Tolkien'
};

const element = (
  <h1>
    Best selling book of all time, {getBookDetails(book )}!
  </h1>
);

ReactDOM.render(
  element,
  document.getElementById('root')
);

JSX as arguments and return values

JSX can be put inside If statements, as function arguments, or function return values. Below is a simple example where we are using JSX as function return values.

function showBookDetails(book) {
  if (book) {
    return <h1>Awesome book, {getBookDetails(book)}!</h1>;
  }
  return <h1>Unknown book.</h1>;
}

How to provide Attributes with JSX

You can use quotes to provide string literals as attributes to JSX element. Here we are providing type attribute as tel.

const element = <input type="tel">;

You can use curly braces when you want to put an expression as attributes to JSX element.

var telephone = {
                 type: 'tel',
                 state: 'good' 
                };
const element = <input type={telephone.type}>;

Never put quotes around curly braces while embedding javascript expression. Rule of thumb is either use quotes for string values or curly braces for expressions, never both.

JSX can contain many children. And their children can also contain children. Below is a simple example.

const element = (
  <div>
    <h1>Hi!</h1>
    <h2>How are you doing.</h2>
    <h3>I am doing fine</h3>
    <p>This is nice para inside hey look I'll put a <span>Small span</span> as well in this</p>
  </div>
);

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

About anil

Hi, I'm Anil Verma. I have a passion for teaching and developing awesome front end apps. I was involved in development of post processor for Nastran(built by NASA). More recently I have been building supply chain apps at E2open.
View all posts by anil →

Leave a Reply

Your email address will not be published. Required fields are marked *