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 component so it returns a heading element that displays Hello World.

// File: App.tsx located in app-name/src/
 
export default function App() {
  return <h1>Hello World</h1>;
}

Example 2: Center Align Hello World

You can align text to the center using two approaches.

Important Note: Remove all lines from both App.css and index.css to avoid conflicts. Both files are located in app-name/src/

Method 1: Inline Styling

Use inline CSS with textAlign: "center".

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

Method 2: External CSS

// File: App.tsx located in app-name/src/
 
import "./App.css";
 
export default function App() {
  return <h1 className="appcenter" style={{color: "red"}}>Hello World</h1>;
}
/* File: App.css located in app-name/src/   */
 
.appcenter{
    text-align: center;
}

Method 3: Global CSS file index.css

/* File: index.css located in app-name/src/   */
 
.appcenter{
    text-align: center;
}

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: App.tsx located in app-name/src/
 
export default function App() {
  return <h1>Your Name</h1>
        <p>Introduction about myself</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: App.tsx located in app-name/src/
 
export default function App() {
  return ( 
    <div>
      <h1>Your Name</h1>
      <p>Introduction about myself</p>
    </div>
  );
}

Solution 2

// File: App.tsx located in app-name/src/
 
export default function App() {
  return ( 
    <>
      <h1>Your Name</h1>
      <p>Introduction about myself</p>
    </>
  );
}

Example 5: Multiple Inline Styles

You can apply multiple CSS properties using inline styling.

Key Points:

// File: App.tsx located in app-name/src/
 
export default function App() {
  return (
      <div>
        <h1 style={{color: "red", textAlign: "center", marginTop: '10px'}}>Hello World</h1>
      </div>
    );
}

Example 6: Displaying Image

To display an image:

Best Practices:

Additional Notes:

// File: App.tsx located in app-name/src/
 
export default function App() {
  return (
      <div>
          <div> {/*outer-container*/}
              <div style={{width:"107px", height:"142px", border:"1px solid black"}}> {/*image-container*/}
                  <img src="../src/assets/hero.png" alt="A sample Logo" style={{maxWidth:"100%", height:"auto"}} />
              </div>
          </div>
      </div>
  );
}