What's the purpose of <div className="App"> in a React class render function?

Viewed 2109

I'm new to React, and so far I understand that className in React jsx can be a reference to an html class defined in an imported css file. Like className="warning" in the following example, which makes the text display red instead of the default black.

But I'm also seeing, in numerous tutorial examples, elements like <div className="App"> appearing at the top of the render() function. This typically doesn't reference anything in the imported css file, yet it can often be present even if there is no imported css file in the example at all.

Indeed I find that if I replace it with just <div>, the example renders exactly as before. So what do elements like <div className="App"> do, and what are they for?

App.js

import React, { Component } from 'react';
import './App.css';

class App extends Component {
    render() {
        return (
            <div className="App">
                <h1 className="warning">Wakeup World!</h1>
            </div>
        )
    }
}

export default App;

App.css

.warning {
    color: red
}
3 Answers

I believe that this is just a convention, it does not pertain to React's internal rendering logic or anything like that.

To answer your question about why they are there, its for global styling changes that are a little more specific than html or body. Again, a convention that you can feel free to ignore.

Source: https://reactjs.org/docs/rendering-elements.html and related docs

The purpose of <div className="App"> is nothing else but rendering a <div> using App as the class. If there's no styling linked to that className, you'd get the same result when changing it.

Since React has no official naming conventions, there isn't any official document that says that the first element must be a <div> containing the class App

I guess this has become some sort of unspoken rule.

Even Facebooks create-react-app uses App as the first element. (Source)

However, React's tic-tac-toe tutorial doesn't use the App as first element, rather just a <div className="Game"> as it would make more sense.

Render div with class "App"

return (
         <div className="App">
           <h1 className="warning">Wakeup World!</h1>
         </div>
       )

Render h1 with class "warning"

return (
         <>
           <h1 className="warning">Wakeup World!</h1>
         </>
       )

or

return (
           <h1 className="warning">Wakeup World!</h1>
       )

This is the syntax of JSX, similar to html and renders what you ask. The examples use the default autogenerated template with `.., but this is not at all necessary

Related