JSX Short Examples:
const h1 = <h1>Hello world</h1>;
const navBar = <nav>I am a nav bar</nav>;
JSX stored as an Object:
const navbar = {
home: <li>Home</li>,
about: <li>About</li>,
contact: <li>Contact</li>,
signUp: <li>Sign Up</li>
};
JSX is a language made to be used with React. Written in JS files and treated as JavaScript expressions. Add JavaScript code to JSX elements using curly braces { }.
const example = (
<>
<h1> Header Title <h1>
<p> Paragraph </p>
</>
);
JSX expressions must have an outermost element. Either <div> </div> or fragments <> </> could be used in order for it to render.
Some examples:
const element = <a href="www.com"> link </a>;
const img1 = <img src={imgSavedToAVar}></img>;
Example using camelCase:
<button className="styleButton" onClick={func}> Click </button>
React uses camelCase naming convention to use HTML Attributes. Ex: tabindex = tabIndex, onclick = onClick
Old method:
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(<h1>Hello world</h1>, document.getElementById('app'));
New method:
import React from 'react';
import { createRoot } from 'react-dom/client';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<App />);
To render JSX inside a HTML DOM element.
<br /> // Represents a line break
<hr /> // Represents a horizontal rule or divider
<img src="" alt="" /> // Represents an image
<input type="" /> // Represents an input element
All tags must be properly closed, but some tags are self-closing tags.
const example = (
<a href="https://link.com">
<h1>
Click here
</h1>
</a>
);
Use parentheses if you have nested multiline JSX.
const name = 'First Name';
const element = <h1>Hello, {name}</h1>;
Clock example:
function Clock() {
const date = new Date()
const hours = date.getHours() % 12
return (
<h1>It is currently about {hours} o'clock!</h1>
)
}
Image example:
<img src={`../images/${props.img}`} />
To use JavaScript in JSX use curly braces.