What is an element in ReactJS

Rumman Ansari   2022-12-15   Developer   react js > What is an element   314 Share

What is an element?

  • As we have discussed, they form the basic block of the React app.
  • They have the information that is displayed in UI.

Example:


const element = <h1>Hello, world</h1>;

Here 

<h1>.....</h1>  is an element that has the data Hello world.

Here is how we create and use an element in React.


const user = {
  name: 'Harry'
};
const myElement = (
  <h1>
    Hello, {user.name}!
  </h1>
);
ReactDOM.render(
  myElement,
  document.getElementById('root')
);
Nested Elements
  • You can return only one element at a time in a component
  • More than one element can be wrapped up inside a container element E.g. <div>...</div>
  • The following code is an example of Nested elements. You could see Hello! and Welcome..... are 2 elements nested within the element myMsg.

const myMsg = (
  <div>
    <h1>Hello!</h1>
    <h2>Welcome to the React Tutorial on Fresco Play!</h2>
  </div>
);
ReactDOM.render(
  myMsg,
  document.getElementById('root')
);
Rendering Elements

An element describes what you want to see on the screen.


const myMsg = <h1>Hello, world</h1>;

Rendering an element into the DOM

Let us say, there is a 

 somewhere in your HTML file:


<div id="root"></div>
  • Everything inside root will be managed by React DOM.
  • Applications built with just React usually have a single root DOM node.
  • To render a React element into a root DOM node, pass both (i.e. element and node) to ReactDOM.render():
Expressions in JSX

All the javascript expressions can be used in JSX by enclosing the expressions inside curly braces.

Example


function formatName(user) {
return user.firstName + ' ' + user.lastName
}
const user = {
  firstName: 'Harry',
  lastName: 'Potter'
};
const element = (
  <h1>
    Hello, {formatName(user)}!
  </h1>
);
ReactDOM.render(
  element,
  document.getElementById('root')
);

Here formatName(user) is an expression and is enclosed within braces.