JSX & React Component Basics

What’s JSX?

const div= <div>Hello world</div>;

JSX .map()

const stringsArray = ['Milk', 'Sugar', 'Nutella'];

const list = stringsArray.map(string => <li>{string}</li>);

<ul>{list}</ul>

JSX Event Listeners

//JSX attributes
const example = <h1 id="attributeName">JSX Attributes</h1>;
// basic without event parameter
const handleClick = () => alert("Hello world!");

const button = <button onClick={handleClick}>Click here</button>;

// Example with event parameter
const handleMouseOver = (event) => event.target.style.color = 'purple';

const button2 = <div onMouseOver={handleMouseOver}>Drag here to change color</div>;

What’s a component ?

A React component is a reusable piece of code that’s used to change or define the appearance, behavior, and state of a portion of a web applications UI. Components are functions or classes.

import React from 'react';

function MyFunctionComponent() {
return <h1>Hello from a function component!</h1>;
}

class MyClassComponent extends React.Component {
render() {
return <h1>Hello from a class component!</h1>;
}
}

JSX Capitalization

In react the first letter of components has to be capitalized. JSX can use this capitalization to tell the difference between an HTML tag and a component instance. If the first letter of a name is capitalized, then JSX knows it’s a component instance; if not, then it’s an HTML element.

// This is a JSX HTML tag 
<div>
// this is react component
<ThisComponent />

import React

For us to be able to use react, we have to import the react library. After we import the library it creates an object that contains properties thats needed to make react work. which includes custom components and JSX. importing from ‘react’ doesn't let you interact with the DOM. All the methods imported from ‘react’ are only for react like creating components and writing JSX elements. But if we want to interact with the DOM we want to import from ‘react-dom’ also.

import React from 'react';

import ReactDOM

The import ReactDOM is kind of similar to import React. They both import JavaScript objects. But there is a slight difference between the two. ‘react-dom’ is just for interacting with the DOM. The DOM is used in react applications, but technically isn’t apart of react. The can be used in other applications other than react.

import ReactDOM from 'react-dom';

render()

React class components needs to have a render() method which needs a return. This returns some react elements that was created with JSX. Also the react class components need to inherit from the React.Component base class.

import React from 'react';
import ReactDOM from 'react-dom';
class MyComponent extends React.Component {
render() {
return <h1>Hello World!!</h1>;
}
}

Currently Studying to be a Software Engineer At Flatiron.