Home > Enterprise >  Why react use angular brackets in rendering the component
Why react use angular brackets in rendering the component

Time:12-17

I am new to the react as my background is ruby, so maybe it look a silly or noob question. i come to the article "Every component must begin with a capital letter. And once a component is declared, it can be written and used very similarly to an HTML element." and also this "To use this component in your application, use similar syntax as normal HTML: "

class Car extends React.Component {
  constructor() {
    super();
    this.state = {color: "red"};
  }

 render() {
    return <h2>I am a {this.state.color} Car!</h2>;
  }
}

root.render(<Car color="red"/>);

we have a car component created using class component so my question here is Why we use angular bracket here for creating instance of Car class. is this a syntax of creating instance of class in react. Or To use this component we have to use similar syntax as HTML. why?

CodePudding user response:

React uses angular brackets () in rendering an element as a result it permits you to incorporate the element as a JSX part. JSX may be a syntax extension for JavaScript that permits you to write down HTML-like code in your JavaScript files. it's not obligatory to use JSX with React, however, it's a preferred alternative, as a result, it makes it easier to grasp the structure of your elements and the way they relate to the DOM.

To render an element in React, you'll use the ReactDOM.render() methodology and pass it to the element you wish to render further as a DOM part.

import React from 'react';
import ReactDOM from 'react-dom';

const MyComponent = () => <h1>Hello, World!</h1>;

ReactDOM.render(<MyComponent />, document.getElementById('root'));

The MyComponent operation is wrapped in angular brackets () and passed to the ReactDOM.render() methodology as a JSX part. This tells React to treat the operation as an element and render it within the DOM part with the id of the root.

CodePudding user response:

Hopefully this helps. Before React we needed an index.html File and had to call your javascript.js file within your HTMLenter image description here. example: in HTML, if we wanted to select a Button in javascript and add an onClick event we had to call the button but be specific as possible, so we had to add a class,ID, etc... Import your button to your javascript file like car= document.getElementById("car1") and then add a onclick event. as you can see this can be exhausting. worst part is you cant add HTML in your Js file, so no

tags, etc.. so the way to make things easier in HTML is adding brackets. React allows you to use HTML and Js syntax. in your example: return

I am a {this.state.color} Car!

; we are telling React we have h2 from HTML but anything within { } is Javascript. as you can see React just makes easier to use HTML and javascript in the same file

  • Related