React Render HTML

React renders HTML using ReactDOM.render().

React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.

import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            <Header/>
            <Content/>
         </div>
      );
   }
}
class Header extends React.Component {
   render() {
      return (
         <div>
            <h1>Header</h1>
         </div>
      );
   }
}
class Content extends React.Component {
   render() {
      return (
         <div>
            <h2>Content</h2>
            <p>The content text!!!</p>
         </div>
      );
   }
}
export default App;

 

Root document

The root node is the HTML element where you want to display the result.

ReactDOM.render(
        <Providerstore={createStore(allReducers, applyMiddleware(thunk))}>
              <React.StrictMode>
                    <Router>
                          <Routepath="/"exactcomponent={Home}/>
                    </Router>
              </React.StrictMode>
        </Provider>,
        document.getElementById('root')
);

 

// HomeComponent
<body> 
     <header id="root"></header> 
</body>

 

Conditional Rendering
You can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application.
function UserWelcome(props) {
  return <h1>Welcome back!</h1>;
}

function GuestWelcome(props) {
  return <h1>Please sign up.</h1>;
}
class Content extends React.Component { 

   render() {
      if (this.state.isLoggedIn) {
         return <UserWelcome />;
      }
      return <GuestWelcome />;
   } 
} 

export default App;

Create Functions in render()

It’s generally a bad idea to create new functions to pass into props in the render function.

The reason it’s bad to create new functions is for performance: not because functions are expensive to create, but because passing a new function down to a pure component every time it renders means that it will always see “new” props, and therefore always re-render (needlessly).

Avoid creating a new function in render when:

  • (a) the child component receiving the function prop is pure and
  • (b) you expect the parent component to re-render often.

Function components and classes that extend Component are not pure. They will always re-render, even if their props haven’t changed. If a class extends PureComponent instead, though, it is pure and it will skip re-rendering when its props are unchanged. Avoiding needless re-renders is the easiest way to improve performance in a React app.




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

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