How to Display Text in React Js

React.js is a popular JavaScript library for building user interfaces. One common task when developing web applications with React.js is displaying text on the screen. In this article, we will explore different ways to display text in React.js and provide you with the knowledge you need to get started.

Using JSX

In React.js, JSX is a syntax extension that allows you to write HTML-like code within your JavaScript. You can use JSX to display text by wrapping it in HTML elements. Here’s an example:

import React from 'react';

function App() {
  return (
    <div>
      <h1>Hello, React.js!</h1>
      <p>Welcome to the world of React.js</p>
    </div>
  );
}

export default App;

In the above code, we have used the <h1> and <p> elements to display text. You can replace the text inside these elements with your desired content. Save the file with a .js extension and render the App component to see the text displayed on the screen.

Using JavaScript Variables

Sometimes, you may need to display dynamic content in React.js, such as text stored in a JavaScript variable. You can achieve this by using curly braces {} to wrap the JavaScript expression within JSX. Let’s see an example:

import React from 'react';

function App() {
  const greeting = 'Hello, React.js!';
  const description = 'Welcome to the world of React.js';

  return (
    <div>
      <h1>{greeting}</h1>
      <p>{description}</p>
    </div>
  );
}

export default App;

In the above code, we have defined two Javascript variables, greeting and description, and used them inside the JSX elements. The values of these variables will be displayed as text on the screen.

Using Props

In React.js, components can send data from parent to child through props. You can pass text as a prop to a child component and display it within that component. Here’s an example:

import React from 'react';

function Greeting(props) {
  return <h1>{props.text}</h1>;
}

function App() {
  return (
    <div>
      <Greeting text="Hello, React.js! Greetings from the props!" />
    </div>
  );
}

export default App;

In the above code, we have created a child component called Greeting that receives a prop called text. The value of the prop is displayed as text within the <h1> element of the Greeting component.

author's bio photo

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.