For most people who write React application, the starting point is usually with npx or create-react-app CLI. I am not different from this group, I kicked off learning react using CLI tools without prior knowledge of how React works under the hood. Although there is nothing wrong with this, there are a few perks to knowing how React works without the fancy tools and packages that come with the CLI boilerplate.
I will be walking you through the most basic parts of building pure react apps with React CDN. Create a basic HTML file and insert a div with the id root, you can name the id anything but, I chose root because of popular convention and practice π.
After this go over to (https://reactjs.org/docs/cdn-links.html) and grab the CDN links for React and React-dom. You have options to choose from development and production. Now create a .js file and link it beneath the CDN files, at this point your HTML file should be looking like this.
Now that we have our HTML and JavaScript file set up let's start writing pure React codes :-D.
Open up the Js file and declare a function(App) just like you'd normally do with boilerplate React app. Inside your function return React.createElement('p', {}, 'Hello World').
I know it is all starting to look weird and new to you but if you look closely, you notice something familiar(createElement), this is the same API used in creating new DOM elements in javascript. Now let me break everything down.
The React.createElement Method is passed 3 parameters.
- The first one is the element tag that you are creating.
- The second parameter holds the properties of the element (props, classes, id).
- The third parameter holds the children of the element, in this case, it is the string 'Hello World'.
How exactly do we get this to render/make it display in the browser? that is the power of the react-dom. Just under the App function, insert this : ReactDOM.render(React.createElement(App), document.getElementById('root'));
If you look at the line of code, you will notice that the App component/function is created before gluing it to the HTML page using the react-dom, the ReactDOM.render takes two parameters; The first parameter holds the component while the id of the DOM element that the component is to be appended in goes inside the second parameter.
The react-dom serves as a glue, it takes the component and renders it inside the element passed in the second parameter.
If you have followed all these steps, congratulations you just wrote your first code using pure react.
I will dive deeper and review how to pass in properties and multiple child elements using pure React in the next part.
Make sure to leave a Reaction and Follow π, Thank you.
Top comments (0)