1.

Explain JSX in React?

Answer»

JSX is used in React to write code instead of regular JavaScript. It is similar to JavaScript but actually an extension to it. JSX Allows us to include ‘HTML’ in the same file along with ‘JavaScript’ (HTML+JS=JSX).

JSX LOOKS like regular HTML and we have used it in Question 1.

import React from ‘react’; import Header from ‘./HeaderPage’; import Footer from ‘./FooterPage’; CONST AboutPage =() => { return( <div>  <Header />   <h1>About Us</h1>   <p>We are a cool web development company, located in Silicon Valley.</p>  <Footer /> </div> ) }; export default AboutPage;

In the above example inside the return statement, we are using JSX. Notice, the <div> is used to wrap the whole HTML code. It is required or else compiler will throw an error.

JavaScript expressions also can be used inside of JSX. We use it by wrapping them inside a set of curly brackets {}, as in below example.

import React from ‘react’; const DemoPage =() => { return( <div>   <h1>{1+1}</h1> </div> ) }; export default DemoPage;

Gives output - 2

We cannot use if-else statement inside JSX, so we use ternary expressions if we need to check condition. In the below example, we TOOK the App.js provided when we create a react app using create-react-app. Here we MODIFIED the code and used a ternary EXPRESSION to check if i is 1, and then display an image or else display the link.

import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component {  render() {    var i =1;    return (      <div className="App">        <header className="App-header">        { i === 1 ?          <img src={logo} className="App-logo" alt="logo" /> :          <a href="https://reactjs.org" target="_blank">            Learn React          </a>        }        </header>      </div>    );  } } export default App;

Gives output -



Discussion

No Comment Found