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
St
is a JSX element created by invoking the Text component. WhenSt
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.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:
The JSX code
<Text/>
gets translated to plain javascript asReact.createElement(Text, null)
1. Calling this function creates an object which describes what you want on the page. The object looks roughly like this: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: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