JavaScript React Basics First Steps in React Render an Element

neftali
neftali
5,294 Points

Like all the comments below, this is not working for me either. Once I called ReatDOM.render(), Nothing.

ReactDOM.render(); method not being called or rending the element on the HTML side.

So, I came at this from already knowing create-react-app (much better to use, by the way). Anyway, I could not get the text "My First React Element!" to display in the browser either. In create-react-app, you import React and React-Dom at the start of each component, and refer to it in the code below, so I was looking for that.

Since it was CDN, I was toying around with stuff and got it to work and found out that my habits from create-react-app bled over into this. When importing React and React-Dom into each component, you also assign it a variable name. I got into the habit of naming my variable fro React-Dom, "ReactDom".

So, when starting out, I did this:

ReactDom.render(
    title,
    document.getElementById('root')

I did not get anything rendered on the browser, and got an error in my console. So below is my finished code for the app.js file. All I did was change from "ReactDom.render()" to "ReactDOM.render()"

const title = React.createElement(
    'h1', 
    { id: 'main-title', title: 'This is a Title.' },
    'My First React Element!'
)

ReactDOM.render(
    title,
    document.getElementById('root')
)

2 Answers

robin blaauw
robin blaauw
2,062 Points

I would advise you to take a loot at your setup. This gave me issues as well so I decided to use NPM to create the project. Ill try and walk you through what i did to get it working.

You will need nodejs for this, if you don't have that visit: https://nodejs.org/en/

Now open your command prompt and type npm i -g create-react-app. After you install that package go to the folder you want for your project. For me it's C/Documents/Coding. Type npx create-react-app my-app. Note that npx is not a typo.

This will create your react app. Visit your folder, go to src and type del * if you are on windows or rm -f * when on windows or mac. Now add 2 files in the folder src. index.css, that you can leave empty and index.js

copy this code to index.js:

import React from "react"; import ReactDOM from "react-dom"; import "./index.css";

const title = React.createElement( "h1", { id: "main-title" }, "my first react element" );

console.log(title);

// ========================================

ReactDOM.render(title, document.getElementById("headingFirst"));

Let me know if this works.

Regards, Robin

Michael Cook
Michael Cook
Full Stack JavaScript Techdegree Student 25,018 Points

This answer would have been more helpful if you put your code in markdown to show exactly what you did. Thanks for trying though. I followed your instructions and got nothing on my screen.

Waylan Sands
PRO
Waylan Sands
Pro Student 5,823 Points

Make sure your scripts are in the bottom of the body, not the head!