skip to Main Content
const Text = () => <p style={{ fontFamily: "Inter" ,color:"azure" }}>Hello world!</p>;

export  function App(){
   const St = <Text/>;
   console.log(St)
   return (<>{St}</>)
}

It prints hello world.

My question: what is St in this code? Why can we render St in return statement just as it is?

3

Answers


  1. St is a JSX element created by invoking the Text component. When St is rendered in the return statement, it renders the JSX element represented by Text. JSX allows you to directly render components or HTML-like elements in your React applications. So, St can be rendered directly in the return statement because it represents a valid JSX element. When App component is rendered, it will display "Hello world!" as specified in the Text component.

    Login or Signup to reply.
  2. Here, St is a state. States in JSX documents can be understood as variables that are recalculated every time the page is rendered. If you expect St to be recalculated every time the document is re-rendered, this usage is correct. However, if you only want it to re-render when the variables inside St change, you should use it as follows:

    const Text = () => <p style={{ fontFamily: "Inter", color: "azure" }}>Hello world!</p>;
    
    export function App() {
      /* Values defined here are considered as state. */
      return <><Text /></>;
    }
    
    Login or Signup to reply.
  3. The JSX code <Text/> gets translated to plain javascript as React.createElement(Text, null)1. Calling this function creates an object which describes what you want on the page. The object looks roughly like this:

    {
      type: Text,
      props: null,
    }
    

    That object is what you are assigning to St.

    After this you create another element, via the code<>{St}</>. That creates an object like this:

    {
      type: React.Fragment,
      props: { 
        children: {
          type: Text,
          props: null,
        }
      }
    }
    

    You then return this object, which lets react know what you want to put on the page. React will then recursively render the child components to find out what a { type: Text, props: null } is supposed to look like.

    1) all examples in this answer are approximate. Different react versions or project setups can change the output slightly, and i’ve omitted some details

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search