0% found this document useful (0 votes)
5 views

React Component

Uploaded by

reni
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

React Component

Uploaded by

reni
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 7

React components

Render HTML in a web page


• React's goal is in many ways to render HTML in a web page.
• React renders HTML to the web page by using a function
called createRoot() and its method render().
• The createRoot Function
• The createRoot() function takes one argument, an HTML element.
To define the HTML element where a React component should
be displayed
• The render Method
To define the React component that should be rendered
Display a paragraph inside an element with the id of
"root"

const container = document.getElementById('root');


const root = ReactDOM.createRoot(container);
root.render(<p>Hello</p>);
The result is displayed in the <div id="root"> element:

<body>
<div id="root"></div>
</body>
Create a variable that contains HTML code and display it in the "root" node:

• const myelement = (
<table>
<tr>
<th>Name</th>
</tr>
<tr>
<td>John</td>
</tr>
<tr>
<td>Elsa</td>
</tr>
</table>
);

const container = document.getElementById('root');


const root = ReactDOM.createRoot(container);
root.render(myelement);
Create Your First Component

• When creating a React component, the component's


name MUST start with an upper case letter.
Class Component
• A class component must include the extends
React.Component statement.
• This statement creates an inheritance to React.Component, and gives
your component access to React.Component's functions.
• The component also requires a render() method, this method returns
HTML.
Example

• Create a Class component called Car


class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
Function Component

• A Function component also returns HTML, and behaves much the


same way as a Class component,
• Function components can be written using much less code, are easier
to understand
• Create a Function component called Car
function Car() {
return <h2>Hi, I am a Car!</h2>;
}

You might also like