Sunday, October 4, 2020

JSX intro and the Fragment

 The JSX part of code contains some minor changes when compared to HTML.

Like, className attribute instead of class and few others.

By default, all the rendered code will be sent to a div tag.


import React, { Component } from "react";
import "./App.css";

class App extends Component {
  render() {
    return (
      <div className="App">
        <h1>Hello from React</h1>
      </div>
    );
  }
}

export default App;

This will create div structure as div root-->div App-->and the h1 tag

So, whatever tags we write should be under the App div part here.Can't be written outside as render function sends as a single part.

If we want to skip this App part of div and send the output to root div tag directly, use below code.


import React, { Component } from "react";
import "./App.css";

class App extends Component {
  render() {
    return (
      <React.Fragment>
        <h1>Hello from React</h1>
        <h2>Goodbye</h2>
      </React.Fragment>
    );
  }
}

export default App;

You can import the Fragment part and change code as
import React, {
  Fragment,
  Component
} from "react";
import "./App.css";

class App extends Component {
  render() {
    return ( < Fragment >
      <
      h1 > Hello from React < /h1> <
      h2 > Goodbye < /h2> < /
      Fragment >
    );
  }
}

export default App;

Instead of Fragment section we can create an empty section also which will be taken as Fragment.
import React, {
  Fragment,
  Component
} from "react";
import "./App.css";

class App extends Component {
  render() {
    return ( <>
      <
      h1 > Hello from React < /h1> <
      h2 > Goodbye < /h2> 
</>
    );
  }
}

export default App;

No comments:

Post a Comment