Author: M Abo Bakar Aslam

Run Custom Code

Before continue this lesson, you can download starting code by using below button. in the code, you can easily run examples of this lesson.

Example 1: Displaying Hello World

Display a simple message. Update the App page so it will displays Hello World.

// File: page.tsx located in app/ directory
 
export default function page() {
  return <h1>Hello World</h1>;
}

Example 2: Center Align Hello World

You can align text to the center using two approaches.

Method 1: Inline Styling

Use inline CSS with textAlign: "center".

// File: page.tsx located in app-name/src/
 
export default function page() {
  return <h1 style={{textAlign: "center"}}>Hello World</h1>;
}

Method 2: External CSS

// File: page.tsx located in app/ directory
 
export default function page() {
  return <h1 className="red-heading stylish-heading" style={{textAlign: "center"}}>Hello World</h1>;
}
/* File: globals.css located in app/ directory   */
 
.red-heading{
  color: blue;
}
.stylish-heading{
  background-color: cyan;
  font-size: 60px;
  font-family: fantasy;
}

Example 3: Multiple Elements Error

If you try to return multiple elements directly (like <h1> and <p>), React throws an error because a component must return a single root element.

// File: page.tsx located in app/ directory
 
export default function page() {
  return <h1>Hello World</h1>
  <p>Learning Web Development using NextJS TypeScript</p>
}

Example 4: Fix Using Container / Fragment

To fix the error, wrap elements inside:

This ensures only one parent element is returned.

Solution 1

// File: page.tsx located in app/ directory
 
export default function page() {
  return (
    <div>
      <h1>Hello World</h1>
      <p>Learning Web Development using NextJS TypeScript</p>
    </div>
  );
}

Solution 2

// File: page.tsx located in app/ directory
 
export default function page() {
  return (
    <>
      <h1>Hello World</h1>
      <p>Learning Web Development using NextJS TypeScript</p>
    </>
  );
}

Example 5: Multiple Inline Styles

You can apply multiple CSS properties using inline styling.

Key Points:

// File: page.tsx located in app/ directory
 
export default function page() {
  return <h1 className="red-heading stylish-heading" style={{textAlign: "center", margin: "50px", padding: "20px"}}>Hello World</h1>;
}