Home > database >  Simple explanation as to why this code wouldn't work
Simple explanation as to why this code wouldn't work

Time:06-03

Started to get into react as a part of my BA thessis, need some code as examples but don't want them to be generic, so if someone could please explain as to why this wouldn't work it would be very helpfull, thanks!

import React from 'react';
import ReactDOM from 'react-dom/client';

function Greetings(props){
    return <h1> hello!  {props.name}</h1>;
}

const element = <Greetings name ='Sarah' />;
document.getElementById('root').innerHTML = element.props(name);

CodePudding user response:

element is a small object describing what you want to be on the page. Basically, it looks like this:

const element = {
  type: Greetings,
  props: { name: 'Sarah' }
}

This is not something you are intended to use directly. There is no direct way to figure out that Greetings will contain an <h1>, or that it will be constructing a string "hello! Sarah". The way to put this element on the page is for react to render it. React will recursively walk down the tree of elements, rendering as needed, and then it will compare what changed and update the DOM.

In react 18, this is done as follows:

import { createRoot } from 'react-dom/client'

const root = createRoot(document.getElementById('root'));
const element = <Greetings name ='Sarah' />;
root.render(element)

root.render is typically called exactly once in your app, and from then on you set state to cause rerenders.

CodePudding user response:

import React from 'react';
import ReactDOM from 'react-dom/client';

function Greetings(props){
    return <h1> hello!  {props.name}</h1>;
}

const element = <Greetings name ='Sarah' />;
ReactDOM.render(element, document.getElementById('root'));

https://www.pragimtech.com/blog/reactjs/introduction-to-react-elements/ This may help you.

  • Related