Hi dev,
In this article we will learn about React
Js.
React is a JavaScript library for building a reusable user interface(UI). It was initially released on May 29, 2013. The current version is 16.13.1 and somehow it is stable. React was created by Facebook. React makes creating UI components very easy. The official React documentation can be found here. When we work with React we do not interact directly with the DOM. React has its own way to handle the DOM(Document Object Model) manipulation. React uses its virtual DOM to make new changes and it updates only the element, that needs changing. Do not directly interact with DOM when you build a React Application and leave the DOM manipulation job for the React virtual DOM. In this challenge, we will develop 10-15 web applications using React. A web application, or a website, is made of buttons, links, forms with different input fields, header, footer, sections, articles, texts, images, audios, videos and boxes with different shapes. We use react to make a reusable UI components of a website.
To summarize:
React is one of the most popular JavaScript libraries. Many developers and companies have been using it for the last couple of years. Its popularity has been growing fast and it has a huge community. How do we measure popularity? One measure of popularity could be GitHub repository stars, watchers and forks. Let us compare the popularity of React and Vue. As of today, the popularity between the two most popular JavaScript looks like as shown on the diagram. From the diagram, you can speculate the most popular JavaScript library. You may look at the number of watchers, stars and forks for both React and Vue. These alone will not be a very good measure of popularity, but still it tells a little bit about the popularity of the two technologies. If I have to recommend another JavaScript library next to React, it would be Vue.js.
React Official GitHub Repository
Vue Official GitHub Repository
React Official GitHub Repository
Vue Official GitHub Repository
Why we choose to use React ? We use it because of the following reasons:
JSX stands for JavaScript XML. JSX allows us to write HTML elements with JavaScript code. An HTML element has an opening and closing tags, content, and attribute in the opening tag. However, some HTML elements may not have content and a closing tag - they are self closing elements. To create HTML elements in React we do not use the createElement() instead we just use JSX elements. Therefore, JSX makes it easier to write and add HTML elements in React. JSX will be converted to JavaScript on browser using a transpiler - babel.js. Babel is a library which transpiles JSX to pure JavaScript and latest JavaScript to older version. See the JSX code below.
// JSX syntax
// we don't need to use quotes with JSX
const jsxElement = <h1>I am a JSX element</h1>
const welcome = <h1>Welcome to 30 Days of React Challenge</h1>
const data = <small>Oct 2, 2020</small>
The above strange looking code seems like JavaScript and it seems like , but it is not JavaScript and it seems like HTML but not completely an HTML element. It is a mix of JavaScript and an HTML elements. JSX can allow us to use HTML in JavaScript. The HTML element in the JSX above is h1 and small.
As you have seen in the example above, JSX has a JavaScript and HTML like syntax. JSX element could be a single HTML element or many HTML elements wrapped in a parent HTML element.
This JSX element has only one HTML element which is h1.
const jsxElement = <h1>I am a JSX element</h1> // JS with HTML
Let's make more JSX elements by declaring a new variable named title and content inside h2.
const title = <h2>Getting Started React</h2>
Let us add a subtitles and other contents to this JSX element by adding additional HTML elements. Every HTML element should be wrapped by an outer HTML element to create a valid JSX element. The name title variable also should be changed to header because our JSX element is containing almost all of the header of the application.
const header = (
<header>
<h1>Welcome to 30 Days Of React</h1>
<h2>Getting Started React</h2>
<h3>JavaScript Library</h3>
</header>
)
Let us keep adding more elements. Additional HTML elements to display the author name and year.
const header = (
<header>
<h1>Welcome to 30 Days Of React</h1>
<h2>Getting Started React</h2>
<h3>JavaScript Library</h3>
<p>Asabeneh Yetayeh</p>
<small>Oct 2, 2020</small>
</header>
)
As you can see the header element is a parent element for all the inner HTML elements and JSX must be wrapped by an outer parent element. Without the header HTML element or other parent HTML element the above JSX is invalid.
We comment codes for different reasons and it is also good to know how to comment out JSX elements in React.
{
/*
<header>
<h1>Welcome to 30 Days Of React</h1>
<h2>Getting Started React</h2>
<h3>JavaScript Library</h3>
<p>Asabeneh Yetayeh</p>
<small>Oct 2, 2020</small>
</header>
*/
}
To render a JSX element to HTML document, we should first create an index HTML. The index.html is the only HTML file you will have in any React Application. That is why we say that every React Application is a single page application. Let us create an index.html file. We can get started with React in two ways - either by using CDN or create-react-app. The create-react-app creates a React project boilerplate outbox and because of that, many people do have a hard time to understand how React works. In order to make things clear for absolute beginners I would like to start with a CDN. We use CDN only in this section and we will use the create-reap-app in the rest of the challenge and I also recommend you to use only create-react-app all the time.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>30 Days Of React Challenge</title>
</head>
<body>
<div class="root"></div>
<script></script>
</body>
</html>
As you can see from the above index.html, we have one div with a class root and script. The root div is the gateway to connect all react components to the index.html. In the script tag we will write our JavaScript, but the script type will be babel. Babel will transpile the react JSX to pure JavaScript on the browser. Let us add babel to the script. Inside the babel, we can write any pure JavaScript, JSX and in general any React code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>30 Days Of React Challenge</title>
</head>
<body>
<div class="root"></div>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
// our code goes here
</script>
</body>
</html>
The babel library is linked to our document and now we can make use of it. The next step is importing React and ReactDOM using CDN or link. In order to link React and ReactDOM, we attach both packages from CDN to the body of index.html. To test if React is linked to the index.html, try to check it by doing console.log(React). Open the browser console and you should get an object. If you see an object containing React methods then you managed to link your project with React CDN and you are ready to use React.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>30 Days Of React Challenge</title>
</head>
<body>
<div class="root"></div>
<script
crossorigin
src="https://unpkg.com/react@16/umd/react.development.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
console.log(React)
</script>
</body>
</html>
Now the index.html has everything we need to write React code. Let us get the root element using document.querySelect('.root') and assign it to a variable name rootElement. The is the only place we directly interact with DOM.
Now, you knew JSX and JSX element. Let us render the JSX element on the browser, in order to do so we need the React and ReactDOM library. In addition to the React and ReactDOM we need babel to transpile the JSX to JavaScript code. The ReactDOM package has a method render. The render method takes two arguments:a JSX element or a component and the root document. See the code below. Live on code pen.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>30 Days Of React Challenge</title>
</head>
<body>
<div class="root"></div>
<script
crossorigin
src="https://unpkg.com/react@16/umd/react.development.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
// To get the root element from the HTML document
const rootElement = document.querySelector('.root')
// JSX element
const jsxElement = <h1>I am a JSX element</h1>
// we render the JSX element using the ReactDOM package
// ReactDOM has the render method and the render method takes two arguments
ReactDOM.render(jsxElement, rootElement)
</script>
</body>
</html>
Let us render more content. To render more content, the JSX element should have more HTML elements. For instance, we can create a header of a website and header may have a title, subtitle, author or date etc. Remember, we can render only one JSX element at a time.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>30 Days Of React Challenge</title>
</head>
<body>
<div class="root"></div>
<script
crossorigin
src="https://unpkg.com/react@16/umd/react.development.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
// To get the root element from the HTML document
const rootElement = document.querySelector('.root')
// JSX element
const header = (
<header>
<h1>Welcome to React</h1>
<h2>Getting Started React</h2>
<h3>JavaScript Library</h3>
<p>Asabeneh Yetayeh</p>
<small>Oct 2, 2020</small>
</header>
)
// we render the JSX element using the ReactDOM package
// ReactDOM has the render method and the render method takes two arguments
ReactDOM.render(header, rootElement)
</script>
</body>
</html>
We have created a JSX element for the header of the website. How about the main and the footer for the website? Similar to the header, let us create a JSX element for the main and the footer.
JSX element for the main part of the website.
// JSX element
const main = (
<main>
<p>Prerequisite to get started react.js:</p>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
</main>
)
JSX element for the footer part of the website.
// JSX element
const footer = (
<footer>
<p>Copyright 2020</p>
</footer>
)
Now, we have three JSX elements: the header, main and footer. The best way to render all of the three JSX elements is by wrapping them all in a parent JSX element or putting them in an array. To include JSX element inside another JSX element we use the curly bracket, {} and call the name of the JSX inside the curly bracket.
// JSX element for the header part of the website
const header = (
<header>
<h1>Welcome to 30 Days Of React</h1>
<h2>Getting Started React</h2>
<h3>JavaScript Library</h3>
<p>Asabeneh Yetayeh</p>
<small>Oct 2, 2020</small>
</header>
)
// JSX element for the main part of the website
const main = (
<main>
<p>Prerequisite to get started react.js:</p>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
</main>
)
// JSX element for the footer part of the website
const footer = (
<footer>
<p>Copyright 2020</p>
</footer>
)
// JSX element which contain all, it is a container or parent
const app = (
<div>
{header}
{main}
{footer}
</div>
)
Now, let us put everything together and render it to the browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>30 Days Of React Challenge</title>
</head>
<body>
<div class="root"></div>
<script
crossorigin
src="https://unpkg.com/react@16/umd/react.development.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
// To get the root element from the HTML document
const rootElement = document.querySelector('.root')
// JSX element, header
const header = (
<header>
<h1>Welcome to 30 Days Of React</h1>
<h2>Getting Started React</h2>
<h3>JavaScript Library</h3>
<p>Asabeneh Yetayeh</p>
<small>Oct 2, 2020</small>
</header>
)
// JSX element, main
const main = (
<main>
<p>Prerequisite to get started react.js:</p>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
</main>
)
// JSX element, footer
const footer = (
<footer>
<p>Copyright 2020</p>
</footer>
)
// JSX element, app, a container or a parent
const app = (
<div>
{header}
{main}
{footer}
</div>
)
// we render the JSX element using the ReactDOM package
// ReactDOM has the render method and the render method takes two argument
ReactDOM.render(app, rootElement)
// or
// ReactDOM.render([header, main, footer], rootElement)
</script>
</body>
</html>
Let us apply some style to our JSX elements and see the result.
So far, we did not apply any style in the JSX elements. Now, let us add style to our JSX elements. Inline style became very popular after the emergence of react. Let us add border to the header JSX element.
To add style to a JSX element we use inline style or className. We inject the style object using {}. Every CSS property becomes a key and every CSS property value becomes a value for the the object. For instance, in the example below, border is a key and '2px solid orange' is a value, color is a key and 'black' is a value, fontSize is a key and '18px' is a value. All two word CSS properties will change to camelCase when we use them as key in the CSS object in React or JavaScript.
const header = (
<header
style={{ border: '2px solid orange', color: 'black', fontSize: '18px' }}
>
<h1>Welcome to 30 Days Of React</h1>
<h2>Getting Started React</h2>
<h3>JavaScript Library</h3>
<p>Asabeneh Yetayeh</p>
<small>Oct 2, 2020</small>
</header>
)
// or we can write it this way
const style = { border: '2px solid orange', color: 'black', fontSize: '18px' }
const header = (
<header style={style}>
<h1>Welcome to 30 Days Of React</h1>
<h2>Getting Started React</h2>
<h3>JavaScript Library</h3>
<p>Asabeneh Yetayeh</p>
<small>Oct 2, 2020</small>
</header>
)
It is good practice to open the browser console while you are developing your application to know, if everything goes well.
Let us keep styling all the JSX elements we have created: the header, main and the footer. We can also use regular internal styling to style our application. Using regular style, to target an HTML element we use tag name, id, class, an attribute and other methods. It is very common in the React developer community - people use classes quite a lot instead of id. In this material, I will use only class instead of id.
In JSX element we write className instead of class because class is a reserved word in JavaScript. Similar to className, htmlFor instead of for in label tag. See the example below.
It is good practice to open the browser console while you are developing your application to know, if everything goes well.
Let us keep styling all the JSX elements we have created: the header, main and the footer. We can also use regular internal styling to style our application. Using regular style, to target an HTML element we use tag name, id, class, an attribute and other methods. It is very common in the React developer community - people use classes quite a lot instead of id. In this material, I will use only class instead of id.
In JSX element we write className instead of class because class is a reserved word in JavaScript. Similar to className, htmlFor instead of for in label tag. See the example below.
const title = <h1 className='title'>Getting Started React</h1>
const inputField = (
<div>
<label htmlFor='firstname'>First Name</label>
<input type='text' id='firstname' placeholder='First Name' />
</div>
)
The id used in the input element is not for styling purpose, instead to refer the label to the input field.
If class is used instead of className or for instead of htmlFor you will see such kind of warning.
Now, you know how to use the inline style and how to use className. Let us style all the JSX elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>30 Days Of React Challenge</title>
</head>
<body>
<div class="root"></div>
<script
crossorigin
src="https://unpkg.com/react@16/umd/react.development.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
// To get the root element from the HTML document
const rootElement = document.querySelector('.root')
// style
const headerStyles = {
backgroundColor: '#61DBFB',
fontFamily: 'Helvetica Neue',
padding: 25,
lineHeight: 1.5,
}
// JSX element, header
const header = (
<header style={headerStyles}>
<div className='header-wrapper'>
<h1>Welcome to 30 Days Of React</h1>
<h2>Getting Started React</h2>
<h3>JavaScript Library</h3>
<p>Asabeneh Yetayeh</p>
<small>Oct 2, 2020</small>
</div>
</header>
)
// JSX element, main
const mainStyles = {
backgroundColor: '#F3F0F5',
}
const main = (
<main style={mainStyles}>
<p>Prerequisite to get started react.js:</p>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
</main>
)
const footerStyles = {
backgroundColor: '#61DBFB',
}
// JSX element, footer
const footer = (
<footer style={footerStyles}>
<p>Copyright 2020</p>
</footer>
)
// JSX element, app
const app = (
<div className='app'>
{header}
{main}
{footer}
</div>
)
// we render the JSX element using the ReactDOM package
ReactDOM.render(app, rootElement)
</script>
</body>
</html>
Instead of style object using regular styling method is more easy than the one above. Now, let us use internal style to style all the JSX. It is also possible to use external styling method.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500|Roboto:300,400,500&display=swap"
rel="stylesheet"
/>
<title>30 Days Of React Challenge</title>
<style>
/* == General style === */
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
html,
body {
height: 100%;
line-height: 1.5;
font-family: 'Montserrat';
font-weight: 300;
color: black;
}
.root {
min-height: 100%;
position: relative;
}
.header-wrapper,
.main-wrapper,
.footer-wrapper {
width: 85%;
margin: auto;
}
.header-wrapper,
.main-wrapper {
padding: 10px;
margin: 2px auto;
}
h1 {
font-size: 70px;
font-weight: 300;
}
h2,
h3 {
font-weight: 300;
}
header {
background-color: #61dbfb;
padding: 10px;
}
main {
padding: 10px;
padding-bottom: 60px;
/* Height of the footer */
}
ul {
margin-left: 15px;
}
ul li {
list-style: none;
}
footer {
position: absolute;
bottom: 0;
width: 100%;
height: 60px;
/* Height of the footer */
background: #6cf;
}
.footer-wrapper {
font-weight: 400;
text-align: center;
line-height: 60px;
}
</style>
</head>
<body>
<div class="root"></div>
<script
crossorigin
src="https://unpkg.com/react@16/umd/react.development.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
// To get the root element from the HTML document
const rootElement = document.querySelector('.root')
// JSX element, header
const header = (
<header>
<div className='header-wrapper'>
<h1>Welcome to 30 Days Of React</h1>
<h2>Getting Started React</h2>
<h3>JavaScript Library</h3>
<p>Instructor: Asabeneh Yetayeh</p>
<small>Date: Oct 1, 2020</small>
</div>
</header>
)
// JSX element, main
const main = (
<main>
<div className='main-wrapper'>
<p>
Prerequisite to get started{' '}
<strong>
<em>react.js</em>
</strong>
:
</p>
<ul>
<li>HTML</li>
<li>CSS</li>
<li> JavaScript</li>
</ul>
</div>
</main>
)
// JSX element, footer
const footer = (
<footer>
<div className='footer-wrapper'>
<p>Copyright 2020</p>
</div>
</footer>
)
// JSX element, app
const app = (
<div className='app'>
{header}
{main}
{footer}
</div>
)
// we render the JSX element using the ReactDOM package
ReactDOM.render(app, rootElement)
</script>
</body>
</html>
So far, we used static data on the JSX elements, but we can also pass different data types as a dynamic data. The dynamic data could be string, number, boolean, array or object. Let us see each of the data types step by step. To inject data to a JSX we use the {} bracket.
const welcome = 'Welcome to 30 Days Of React'
const title = 'Getting Started React'
const subtitle = 'JavaScript Library'
const authorFirstName = 'Asabeneh'
const authorLastName = 'Yetayeh'
const date = 'Oct 1, 2020'
// JSX element, header
const header = (
<header>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
Instructor: {authorFirstName} {authorLastName}
</p>
<small>Date: {date}</small>
</div>
</header>
)
Similar to the header JSX element, we can implement data injection to main and footer JSX elements.
Injecting a string to a JSX Element
In this section we inject only strings
const welcome = 'Welcome to 30 Days Of React'
const title = 'Getting Started React'
const subtitle = 'JavaScript Library'
const firstName = 'Asabeneh'
const lastName = 'Yetayeh'
const date = 'Oct 2, 2020'
// JSX element, header
// JSX element, header
const header = (
<header>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
Instructor: {firstName} {lastName}
</p>
<small>Date: {date}</small>
</div>
</header>
)
Injecting a number to a JSX Element
const numOne = 3
const numTwo = 2
const result = (
<p>
{numOne} + {numTwo} = {numOne + numTwo}
</p>
)
const yearBorn = 1820
const currentYear = new Date().getFullYear()
const age = currentYear - yearBorn
const personAge = <p> {age}</p>
As you can see in the example above, it is possible to do some arithmetic calculations and ternary operations.
Injecting an array to a JSX Element
To give an example for an array, let us change the HTML, CSS, JavaScript to an array and inject it to the main JSX element below. We will cover more in much detail later, in rendering lists section.
const techs = ['HTML', 'CSS', 'JavaScript']
// JSX element, main
const main = (
<main>
<div className='main-wrapper'>
<p>
Prerequisite to get started{' '}
<strong>
<em>react.js</em>
</strong>
:
</p>
<ul>{techs}</ul>
</div>
</main>
)
Injecting an object to a JSX Element
We can inject string, number, boolean, array data to JSX but we cannot directly inject an object. We should extract object values first or destructure the content of the object before we inject the data to the JSX element. For instance, let us write firstName and lastName inside an object and extract them to use them inside JSX.
Now, let us put everything together. Here, in the example below, the data is injected dynamically to the JSX.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500|Roboto:300,400,500&display=swap"
rel="stylesheet"
/>
<title>30 Days Of React Challenge</title>
<style>
/* == General style === */
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
html,
body {
height: 100%;
line-height: 1.5;
font-family: 'Montserrat';
font-weight: 300;
color: black;
}
.root {
min-height: 100%;
position: relative;
}
.header-wrapper,
.main-wrapper,
.footer-wrapper {
width: 85%;
margin: auto;
}
.header-wrapper,
.main-wrapper {
padding: 10px;
margin: 2px auto;
}
h1 {
font-size: 70px;
font-weight: 300;
}
h2,
h3 {
font-weight: 300;
}
header {
background-color: #61dbfb;
padding: 10px;
}
main {
padding: 10px 10px 60px;
/* Height of the footer */
}
ul {
margin-left: 15px;
}
ul li {
list-style: none;
}
footer {
position: absolute;
bottom: 0;
width: 100%;
height: 60px;
/* Height of the footer */
background: #6cf;
}
.footer-wrapper {
font-weight: 400;
text-align: center;
line-height: 60px;
}
</style>
</head>
<body>
<div class="root"></div>
<script
crossorigin
src="https://unpkg.com/react@16/umd/react.development.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
// To get the root element from the HTML document
const rootElement = document.querySelector('.root')
// JSX element, header
const welcome = 'Welcome to 30 Days Of React'
const title = 'Getting Started React'
const subtitle = 'JavaScript Library'
const author = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
}
const date = 'Oct 2, 2020'
// JSX element, header
const header = (
<header>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
Instructor: {author.firstName} {author.lastName}
</p>
<small>Date: {date}</small>
</div>
</header>
)
const numOne = 3
const numTwo = 2
const result = (
<p>
{numOne} + {numTwo} = {numOne + numTwo}
</p>
)
const yearBorn = 1820
const currentYear = new Date().getFullYear()
const age = currentYear - yearBorn
const personAge = (
<p>
{' '}
{author.firstName} {author.lastName} is {age} years old
</p>
)
// JSX element, main
const techs = ['HTML', 'CSS', 'JavaScript']
// JSX element, main
const main = (
<main>
<div className='main-wrapper'>
<p>
Prerequisite to get started{' '}
<strong>
<em>react.js</em>
</strong>
:
</p>
<ul>{techs}</ul>
{result}
{personAge}
</div>
</main>
)
const copyRight = 'Copyright 2020'
// JSX element, footer
const footer = (
<footer>
<div className='footer-wrapper'>
<p>{copyRight}</p>
</div>
</footer>
)
// JSX element, app
const app = (
<div className='app'>
{header}
{main}
{footer}
</div>
)
// we render the JSX element using the ReactDOM package
ReactDOM.render(app, rootElement)
</script>
</body>
</html>
As you can see the lists are all in one line. Therefore, we should format the list the way we want, before we inject it to JSX. In order to format the list, we should modify the array before we will inject it to JSX. We can modify the array using map. As a react developer you should have a very good understanding of functional programming(map, filter, reduce, find, some, every). If you don't have good understanding of functional programming, check out Functions in javascript
const techs = ['HTML', 'CSS', 'JavaScript']
const techsFormatted = techs.map((tech) => <li>{tech}</li>)
In the following code example, the list is now containing list elements and it is formatted properly.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500|Roboto:300,400,500&display=swap"
rel="stylesheet"
/>
<title>30 Days Of React Challenge</title>
<style>
/* == General style === */
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
html,
body {
height: 100%;
line-height: 1.5;
font-family: 'Montserrat';
font-weight: 300;
color: black;
}
.root {
min-height: 100%;
position: relative;
}
.header-wrapper,
.main-wrapper,
.footer-wrapper {
width: 85%;
margin: auto;
}
.header-wrapper,
.main-wrapper {
padding: 10px;
margin: 2px auto;
}
h1 {
font-size: 70px;
font-weight: 300;
}
h2,
h3 {
font-weight: 300;
}
header {
background-color: #61dbfb;
padding: 10px;
}
main {
padding: 10px 10px 60px;
/* Height of the footer */
}
ul {
margin-left: 15px;
}
ul li {
list-style: none;
}
footer {
position: absolute;
bottom: 0;
width: 100%;
height: 60px;
/* Height of the footer */
background: #6cf;
}
.footer-wrapper {
font-weight: 400;
text-align: center;
line-height: 60px;
}
</style>
</head>
<body>
<div class="root"></div>
<script
crossorigin
src="https://unpkg.com/react@16/umd/react.development.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
// To get the root element from the HTML document
const rootElement = document.querySelector('.root')
// JSX element, header
const welcome = 'Welcome To React Challenge'
const title = 'Getting Started React'
const subtitle = 'JavaScript Library'
const author = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
}
const date = 'Oct 2, 2021'
// JSX element, header
const header = (
<header>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
Instructor: {author.firstName} {author.lastName}
</p>
<small>Date: {date}</small>
</div>
</header>
)
const numOne = 3
const numTwo = 2
const result = (
<p>
{numOne} + {numTwo} = {numOne + numTwo}
</p>
)
const yearBorn = 1820
const currentYear = new Date().getFullYear()
const age = currentYear - yearBorn
const personAge = (
<p>
{' '}
{author.firstName} {author.lastName} is {age} years old
</p>
)
// JSX element, main
const techs = ['HTML', 'CSS', 'JavaScript']
const techsFormatted = techs.map((tech) => <li>{tech}</li>)
// JSX element, main
const main = (
<main>
<div className='main-wrapper'>
<p>
Prerequisite to get started{' '}
<strong>
<em>react.js</em>
</strong>
:
</p>
<ul>{techsFormatted}</ul>
{result}
{personAge}
</div>
</main>
)
const copyRight = 'Copyright 2020'
// JSX element, footer
const footer = (
<footer>
<div className='footer-wrapper'>
<p>{copyRight}</p>
</div>
</footer>
)
// JSX element, app
const app = (
<div className='app'>
{header}
{main}
{footer}
</div>
)
// we render the JSX element using the ReactDOM package
ReactDOM.render(app, rootElement)
</script>
</body>
</html>
Rendering lists
As you can see above, now the lists are formatted properly, but there is a warning on the console, which says each list child should have a unique key. In the array, we do not have id, but it is common to pass id as a unique value, when you have id in your data. Now, let us just pass each item with a unique key to remove the warning.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500|Roboto:300,400,500&display=swap"
rel="stylesheet"
/>
<title>30 Days Of React Challenge</title>
<style>
/* == General style === */
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
html,
body {
height: 100%;
line-height: 1.5;
font-family: 'Montserrat';
font-weight: 300;
color: black;
}
.root {
min-height: 100%;
position: relative;
}
.header-wrapper,
.main-wrapper,
.footer-wrapper {
width: 85%;
margin: auto;
}
.header-wrapper,
.main-wrapper {
padding: 10px;
margin: 2px auto;
}
h1 {
font-size: 70px;
font-weight: 300;
}
h2,
h3 {
font-weight: 300;
}
header {
background-color: #61dbfb;
padding: 10px;
}
main {
padding: 10px;
padding-bottom: 60px;
/* Height of the footer */
}
ul {
margin-left: 15px;
}
ul li {
list-style: none;
}
footer {
position: absolute;
bottom: 0;
width: 100%;
height: 60px;
/* Height of the footer */
background: #6cf;
}
.footer-wrapper {
font-weight: 400;
text-align: center;
line-height: 60px;
}
</style>
</head>
<body>
<div class="root"></div>
<script
crossorigin
src="https://unpkg.com/react@16/umd/react.development.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
// To get the root element from the HTML document
const rootElement = document.querySelector('.root')
// JSX element, header
const welcome = 'Welcome to 30 Days Of React Challenge'
const title = 'Getting Started React'
const subtitle = 'JavaScript Library'
const author = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
}
const date = 'Oct 2, 2020'
// JSX element, header
const header = (
<header>
<div className='header-wrapper'>
<h1>{welcome}</h1>
<h2>{title}</h2>
<h3>{subtitle}</h3>
<p>
Instructor: {author.firstName} {author.lastName}
</p>
<small>Date: {date}</small>
</div>
</header>
)
const numOne = 3
const numTwo = 2
const result = (
<p>
{numOne} + {numTwo} = {numOne + numTwo}
</p>
)
const yearBorn = 1820
const currentYear = 2020
const age = currentYear - yearBorn
const personAge = (
<p>
{' '}
{author.firstName} {author.lastName} is {age} years old
</p>
)
// JSX element, main
const techs = ['HTML', 'CSS', 'JavaScript']
const techsFormatted = techs.map((tech) => <li key={tech}>{tech}</li>)
// JSX element, main
const main = (
<main>
<div className='main-wrapper'>
<p>
Prerequisite to get started{' '}
<strong>
<em>react.js</em>
</strong>
:
</p>
<ul>{techsFormatted}</ul>
{result}
{personAge}
</div>
</main>
)
const copyRight = 'Copyright 2020'
// JSX element, footer
const footer = (
<footer>
<div className='footer-wrapper'>
<p>{copyRight}</p>
</div>
</footer>
)
// JSX element, app
const app = (
<div className='app'>
{header}
{main}
{footer}
</div>
)
// we render the JSX element using the ReactDOM package
ReactDOM.render(app, rootElement)
</script>
</body>
</html>
Now, you have a very good understanding of how to create JSX elements and also how to inject data to JSX. In the next section, we will talk about how to use create-react-app and components. Components are more powerful and useful than JSX.
🌕 You are awesome. You have just completed challenges and you are two steps ahead on your way to greatness. Now do some exercises for your brain and for your muscle.
Categories : React
Tags : React Js
buy cheap generic tricor purchase fenofibrate generic fenofibrate 200mg oral
order cialis 40mg female viagra sildenafil order sildenafil for sale
where to buy ketotifen without a prescription geodon 40mg pills order tofranil
order dipyridamole generic order pravastatin for sale order pravachol 10mg generic
generic meloset order melatonin without prescription buy danocrine 100 mg generic
order dydrogesterone 10 mg sale buy sitagliptin 100mg without prescription buy jardiance 10mg generic
florinef 100 mcg uk order generic bisacodyl 5mg buy loperamide cheap
cost etodolac where can i buy cilostazol buy cilostazol 100 mg online
prasugrel 10 mg tablet prasugrel generic order tolterodine 2mg without prescription
purchase enalapril buy enalapril generic buy cheap generic duphalac
zovirax where to buy purchase xalatan generic buy rivastigmine 3mg online cheap
betahistine 16 mg sale benemid ca generic probalan
premarin medication premarin 600 mg cost sildenafil 100mg ca
cheap prilosec 20mg metoprolol 100mg sale metoprolol cheap
micardis 20mg price buy generic molnupiravir buy molnupiravir 200 mg online cheap
buy tadalafil generic buy cialis for sale sildenafil price
buy cenforce pills order cenforce pills cost chloroquine
order provigil 200mg for sale phenergan generic prednisone 20mg tablet
buy cefdinir online cheap order lansoprazole pill prevacid canada
isotretinoin 20mg pill purchase amoxicillin generic azithromycin tablet
how to get azithromycin without a prescription buy neurontin pills for sale buy gabapentin 600mg online cheap
buy atorvastatin order proventil 100 mcg online amlodipine online buy
play roulette free for fun cash poker online lasix pills
pantoprazole 40mg generic buy lisinopril pill order phenazopyridine 200 mg sale
roulette casino order doxycycline generic albuterol pills
poker sites online roulette game real money ivermectin 9mg
amantadine 100 mg for sale purchase avlosulfon for sale order avlosulfon 100mg generic
online gambling synthroid pill purchase levothyroxine pill
purchase clomid cheap azathioprine 50mg order imuran online
buy methylprednisolone tablets aristocort where to buy buy aristocort 4mg
order levitra generic digoxin 250 mg for sale buy generic zanaflex
coversyl pill buy generic aceon online order fexofenadine for sale
oral phenytoin 100mg flexeril for sale ditropan cost
buy generic baclofen 10mg buy baclofen 10mg for sale buy toradol sale
claritin 10mg generic tritace tablet buy generic dapoxetine
order baclofen generic baclofen oral toradol 10mg ca
where to buy propranolol without a prescription buy cheap inderal plavix sale
amaryl 1mg drug purchase etoricoxib etoricoxib brand
order nortriptyline online methotrexate 2.5mg brand buy acetaminophen 500mg pill
coumadin drug buy paroxetine 20mg generic order metoclopramide 20mg sale
order xenical 60mg without prescription buy orlistat sale diltiazem cheap
purchase famotidine online order generic famotidine 20mg tacrolimus tablet
azelastine 10ml tablet avapro price irbesartan 150mg for sale
nexium 20mg uk nexium 20mg capsules topiramate usa
sumatriptan 25mg over the counter buy imitrex 25mg generic buy avodart online cheap
allopurinol over the counter rosuvastatin 10mg without prescription rosuvastatin pill
cheap ranitidine 150mg order meloxicam online oral celebrex 200mg
buy buspirone medication order ezetimibe online cheap cordarone 200mg us
motilium price cheap domperidone 10mg sumycin 500mg pills
tamsulosin 0.4mg oral simvastatin 20mg drug order zocor generic
buy an essay online cheap write essay service websites for essay writing
diflucan 200mg brand ciprofloxacin 1000mg pill purchase cipro generic
sildenafil 50mg tablet buy sildalis cheap order estradiol sale
order flagyl 200mg generic buy keflex sale cephalexin 500mg sale
lamotrigine 50mg canada order mebendazole generic buy generic vermox for sale
order cleocin 300mg for sale cleocin 300mg for sale order fildena 50mg pill
retin gel canada order retin cream online cheap stendra price
tamoxifen 20mg brand rhinocort price rhinocort tablet
buy tadacip sale order indocin 50mg pill buy indocin 50mg for sale
purchase ceftin pills methocarbamol 500mg sale robaxin 500mg for sale
purchase desyrel pill purchase clindamycin for sale where to buy clindac a without a prescription
lamisil price casino real money free play play roulette for free
cost aspirin 75mg gamble online win real money real money spins
pay to do my assignment awesome college essays buy suprax 200mg sale
purchase essay online pay for paper writing best online casino usa
amoxicillin 250mg us trimox order buy clarithromycin sale
calcitriol order order labetalol 100 mg generic fenofibrate 160mg canada
clonidine drug meclizine 25mg pill order tiotropium bromide for sale
strong acne medication pills buy oxcarbazepine 600mg online order trileptal 600mg
minocycline drug order generic requip 1mg how to get ropinirole without a prescription
buy generic uroxatral over the counter prescription medication for severe allergies antacid prescription drug names
online doctor for insomnia weight loss pills that work online prescription weight loss programs
femara price albendazole pills generic aripiprazole
natural supplements for smoking cessation quitting smoking with nrt timeline pain medications online to buy
buy provera sale cheap praziquantel microzide 25mg uk
valacyclovir 1000 mg for shingles anti diabetic given to paedes new diabetic medicines list
buy cheap periactin buy nizoral 200 mg generic order ketoconazole pill
antifungal cream for pediatric transmitting genital herpes without outbreak popular blood pressure medication recalled
order cymbalta 40mg generic order generic glucotrol 5mg buy provigil 200mg online
medicine for stomach ulcers over the counter what makes stomach ulcers worse order antibiotics online for uti
buy phenergan without a prescription promethazine 25mg cheap ivermectin pills
contraceptive pills cost best outpatient anatibiotic for prostatitis buy priligy 30mg generic
prednisone online deltasone 5mg over the counter amoxicillin 250mg us
safest acid reducer percription medicine for bloating medication that causes gas
oral zithromax buy generic gabapentin 800mg gabapentin 800mg without prescription
order actigall online cheap order zyrtec 10mg without prescription zyrtec pill
strattera 25mg ca buy atomoxetine medication order sertraline 100mg generic
order lasix online cheap order ventolin albuterol 4mg without prescription
escitalopram pills order naltrexone 50 mg for sale buy revia no prescription
brand clavulanate order augmentin 1000mg generic buy clomiphene 50mg sale
ipratropium 100mcg generic dexona buy online linezolid brand
purchase nateglinide without prescription buy atacand cheap candesartan oral
buy vardenafil 20mg plaquenil online order plaquenil 400mg ca
cheap carbamazepine 400mg buy carbamazepine 400mg online cheap oral lincomycin 500mg
order cenforce generic buy glycomet no prescription metformin for sale online
buy duricef 500mg for sale order duricef 250mg online cheap cheap epivir
purchase atorvastatin online order generic norvasc lisinopril 2.5mg price
prilosec 20mg price prilosec 20mg cost buy atenolol generic
buy cabergoline generic order priligy 60mg pills priligy 90mg tablet
oral methylprednisolone triamcinolone 10mg sale buy clarinex 5mg pills
misoprostol pills order cytotec pill order diltiazem pills
buy piracetam generic cost clomipramine 50mg anafranil 50mg usa
buy cheap acyclovir brand rosuvastatin 20mg order crestor pills
sporanox usa buy generic itraconazole over the counter tinidazole for sale
purchase ezetimibe sale buy ezetimibe pills sumycin 250mg ca
order zyprexa generic valsartan 160mg cost valsartan 160mg tablet
buy flexeril pills ketorolac generic ketorolac oral
colcrys 0.5mg brand clopidogrel for sale order methotrexate 5mg online cheap
best acne treatment teenage guys elimite drug prescription acne cream names
allergy medication without side effects azelastine price allergy pills over the counter
strongest nausea medicine septra online order
strongest sleeping pills uk order meloset 3mg online
brand prednisone 20mg order prednisone
heartburn medicine without calcium order zyloprim 300mg sale
nausea medication over the counter buy generic zidovudine
accutane generic order accutane 10mg sale buy absorica online cheap
sleeping pills online buy buy promethazine generic
После недоразумения с подругой решил принести извинения с помощью яркого букета. "Цветов.ру" оказался моим надежным союзником – быстро, красиво, и главное, с душой. Цветы стали настоящим мостом к миру гармонии и понимания. Советую! Вот ссылка https://gfi-udm.ru/blg/ - цветы с доставкой
amoxicillin medication amoxicillin ca buy generic amoxicillin over the counter
zithromax online order zithromax 250mg pills azithromycin 500mg over the counter
cheap gabapentin 100mg order generic neurontin 100mg
azipro 250mg pill azithromycin 250mg price azithromycin 250mg without prescription
buy generic furosemide diuretic order furosemide 40mg sale
brand prednisolone 40mg order generic omnacortil prednisolone order
order amoxicillin 250mg without prescription buy amoxil 250mg sale order amoxicillin 1000mg for sale
doxycycline online doxycycline 100mg canada
buy ventolin inhalator ventolin canada purchase ventolin without prescription
augmentin 375mg sale augmentin 625mg uk
buy levoxyl online cheap buy generic levothyroxine synthroid 100mcg canada
vardenafil online order buy generic levitra online
buy generic clomiphene 50mg buy clomiphene 100mg pills clomiphene oral
zanaflex cheap buy tizanidine 2mg without prescription buy tizanidine 2mg online
rybelsus 14 mg over the counter buy rybelsus generic semaglutide 14 mg tablet
prednisone 10mg ca prednisone 20mg cost deltasone 20mg without prescription
where can i buy rybelsus order semaglutide 14mg for sale order generic rybelsus
oral isotretinoin order accutane for sale order accutane online cheap
С началом здорового питания я понял, как важен дегидратор для сохранения полезных свойств продуктов. Благодарю 'Все соки' за качественный дегидратор, который помогает мне готовить здоровые закуски. https://h-100.ru/collection/degidratory - Дегидратор стал незаменимым устройством на моей кухне!
best allergy for itchy skin brand ventolin inhalator order ventolin 2mg without prescription
cheap amoxicillin pills order amoxicillin 250mg generic purchase amoxicillin pills
cost augmentin 1000mg where to buy augmentin without a prescription amoxiclav oral
azithromycin 500mg cheap order azithromycin pill generic azithromycin 250mg
cost synthroid 150mcg order generic synthroid 150mcg cheap levothroid sale
cost prednisolone 5mg prednisolone 10mg over the counter oral prednisolone 10mg
free welcome spins no deposit free slots games play roulette online real money
vardenafil 20mg sale levitra 20mg cheap vardenafil us
order lyrica 150mg for sale pregabalin order buy pregabalin pills for sale
plaquenil tablet buy hydroxychloroquine 400mg generic generic hydroxychloroquine 200mg
aristocort online buy aristocort 10mg price cheap aristocort 4mg
cialis for men over 50 cialis 40mg tablet tadalafil otc
oral desloratadine how to buy clarinex how to buy clarinex
purchase cenforce pills cenforce for sale buy cenforce 50mg
loratadine order buy generic loratadine 10mg buy loratadine pill
buy generic aralen online order chloroquine 250mg for sale buy generic chloroquine over the counter
order xenical 60mg pill diltiazem 180mg tablet diltiazem order online
oral lipitor 10mg order lipitor order lipitor sale
buy amlodipine 10mg generic order norvasc pill buy amlodipine pills for sale
purchase acyclovir online buy zyloprim 100mg online cheap order zyloprim 100mg pills
order zestril 2.5mg generic buy lisinopril cheap buy zestril 5mg sale
buy rosuvastatin 20mg pill rosuvastatin 20mg uk zetia 10mg pills
buy generic prilosec for sale omeprazole 10mg pill omeprazole brand
buy domperidone for sale purchase motilium generic buy tetracycline medication
order lopressor 50mg generic metoprolol over the counter lopressor 50mg price
how to buy cyclobenzaprine brand flexeril order ozobax online cheap
order generic tenormin 50mg atenolol order purchase atenolol without prescription
cost toradol cheap gloperba buy generic colcrys for sale
buy medrol pill buy medrol 8mg methylprednisolone 8 mg oral