JSX Components
Updated: 03 September 2023
Setting Up ReactJs
To add react to an HTML file we include the following scripts in the head
And in the body we can add a script to render an element as follows
We can also create a ReactJs CodePen by including the above scripts and using the Babel Javascript Preprocessor
What is ReactJs
React is a library that generates the view layer of an application based on its state. These applications are made from React Components which describe the properties and state of UI components
React makes use of a Virtual DOM and when component states are updated the React Library calculates the most efficient way to update the actual DOM
This turns out to be much faster than re-rendering the entire DOM
React Elements
React Elements are Objects that represent a DOM node and are written in JSX
. React elements are different to React components
React elements need to be rendered by the ReactDOM.render()
method, this can be done as follows
Once the DOM is rendered, it will remain the same until the render method is called again
JSX
JSX is a syntax extension on Javascript that allows React Elements to be written in JS with HTML tags
We can see the difference between using JSX and just JS below
Embed JS
Furthermore we can embed javascript expressions inside of elements using curly brackets
Element Attributes
We can also use JSX for element attributes
Note that the " "
in JSX indicates a string literal. Do not use this to pass in JS attributes
Empty Tags
JSX can simply be used with self closing tags as well
Style Objects
As well as to define styles for an element
We can even define an element styles using the curly braces for the style object
Nested Elements
Elements can be nested within other elements, however these need to be wrapped in a single parent element
It is also recommended to surround these with parenthesis in order to avoid semicolon insertion
Also note that certain attributes are named differently in React, for example class
is called className
React Components
React components are reusable components
React has two types of components, namely Functional and Class
Functional Components
Functional components are just functions that output React Elements, by convention the first letter is capitalized and can be created by referencing the component name
Component Properties
Functional components can also have properties such as
Properties can be any type of javascript object, such as:
Anything passed through props
will be accessible
Component Composition
Functional components can include other components inside of them, such as in the following example which will output a list of shopping items
Conditional Rendering
We can render components based on conditional information by simply using if-else
statements or a conditional operator
inline
We can also completely prevent rendering by returning null
or with the &&
operator