NodeJS React Function Component vs Class Component

Mindwatering Incorporated

Author: Tripp W Black

Created: 04/27 at 11:01 PM

 

Category:
NodeJS
Reference

React front-end:
- Generally index.jsx
- Contains JavaScript with one or more import calls to back-end Components that render the App to the web browser

React App back-end:
- App Components which are generally organized into folders such as App/App.jsx
- Data passed using Props (properties) and via a return value
- Back-end makes available its Components via export calls to other Components or the front-end
- Front-end consumes the Components via import calls

Two basic types of Components:
- Class: a class component extends the base (root) React.Component
- Functional: a JS function


Simple Functional (back-end) Component:
/App/HelloApp.jsx

function HelloApp(props) {
return (
<div class='wptitle'><h1>Hello {props.nm}</h1></div>
);
}
export default HelloApp;


Simple Class (back-end) Component:
/App/HelloApp.jsx

// import React.Component
import React from 'react'

class HelloApp(props) extends React.Component {
render() {
<div class='wptitle'><h1>Hello {props.nm}</h1></div>
}
}


Render to the browser DOM root (front-end):
/index.jsx

import { createRoot } from 'react-dom/client';
import HelloApp from './HelloApp';

// add the HelloApp return to the root browser DOM
const root = createRoot(document.getElementById('root'));
root.render(<App nm="Tom Testor" />);



Coding Notes:
- HTML in JSX have to end up as one root (parent) tag or React will return an error:
"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
- The easiest solution is to wrap HTML tags in a containing <div>...</div> if you want it visible in the browser (to use w/CSS) or the fragment suggested <>...</>, which is not visible in the browser.
- Tags like <br> and <img> must self terminate like in XML, like <br/> and <img/> respectively.
- As class is a reserved word in React, the <div class="csswidget">...</div> becomes <div className="csswidget"></div>
- Attributes and stylesheet attributes with dashes are turned into camelCase, except for aria-* and data-* attributes. e.g. backgroundColor instead of background-color
- A variable value can be substitution w/in HTML strings by swapping out the alt="hardcoded string" with alt={variableNm}.
- When you see {{ ... }}, you are seeing a JavaScript object inside the JSX {}.
- Never render a component w/in another one - bad form and performs badly. In other words, under "export default function Bla()", there should not be an indented "function BlaBla()". Bring that function to the top level of the code/file.


previous page

×