Skip to main content

React Quick Start Notes

·1206 words·6 mins·
Development
Table of Contents

This summer I’m committing to learning the most popular framework for web applications, ReactJS. Initially released in May of 2013 by Facebook, this framework has proved to be incredibly capable in building dynamic, large-scale applications for the web browser.

With it’s extensive ecosystem and immense community support, it’s become a must learn for anyone interested in software engineering. That’s why I’m going to be learning it this summer with the goal of deploying a full-stack application using it by the end of the summer.

Only way to achieve that is to get started from the very basics. Here are the notes I’ve taken from the documentation.

Disclaimer: This article was written to be more of a cheatsheet for personal use.

Basic Component Function
#

Components are essentially javascript functions which return javascript. That’s all.

Traits:

  1. Self contained state (minds it’s own business, unless explicitly told not to)

Button.jsx
#

function MyButton() {
  return (
    <button>I'm a button</button>
  );
}

App.jsx
#

The Master App is also just a function.

export default specifies what the main component is in the file.

export default function MyApp() {
  return (
    <div>
      <h1>Welcome to my app</h1>
      <MyButton />
    </div>
  );
}

Here’s what it would look like in one Master ‘App.jsx’.

function MyButton() {
  return (
    <button>
      I'm a button
    </button>
  );
}

export default function MyApp() {
  return (
    <div>
      <h1>Welcome to my app</h1>
      <MyButton />
    </div>
  );
}

JSX vs. JS
#

Rules:*

  1. Must encapsulate all elements within (<> … </>);
  2. break:<br> == <br />

*Likely more rules that I haven’t got down, but this is all the react intro specifies, will see more as I program and learn

Styling
#

Simply link the css file in the ‘index.html’ file and specify css class with “className”.

<img className="avatar" />

Then write css rules as usual in css file

*Will be using tailwind and other component libraries so will prob be avoiding this method in all honesty

Displaying Data
#

Simply create your javascript variables as needed then embed the data in the html using curly braces {…}.

Example:

return (
<>
  <h1>
    {user.name}
  </h1>
  <img
    className="avatar"
    src={user.imageUrl}
  />
</>
);

Profile.jsx

const user = {
  name: 'Hedy Lamarr',
  imageUrl: 'https://i.imgur.com/yXOvdOSs.jpg',
  imageSize: 90,
};

export default function Profile() {
  return (
    <>
      <h1>{user.name}</h1>
      <img
        className="avatar"
        src={user.imageUrl}
        alt={'Photo of ' + user.name}
        style={{
          width: user.imageSize,
          height: user.imageSize
        }}
      />
    </>
  );
}

*Structs in javascript seem to not have to be explicitly called

Conditional Rendering
#

You can render components conditonally using basic javascript if-else/for/while loops as necessary.

Example:

let content;
if (isLoggedIn) {
  content = <AdminPanel />;
} else {
  content = <LoginForm />;
}
return (
  <div>
    {content}
  </div>
);

You can also use the ternary operator and write rendering logic within the embedded javascript.

Example:

<div>
  {isLoggedIn ? (
    <AdminPanel />
  ) : (
    <LoginForm />
  )}
</div>

Finally, you can simply use the && operator if you don’t have/need an else branch.

Example:

<div>
  {isLoggedIn && <AdminPanel />}
</div>

Rendering Lists
#

You can render a list/array of variables using the array.map() function.

Example:

const listItems = products.map(product =>
  <li key={product.id}>
    {product.title}
  </li>
);

return (
  <ul>{listItems}</ul>
);

ListItems.jsx


//Create array of items/implicit structs
const products = [
  { title: 'Cabbage', isFruit: false, id: 1 },
  { title: 'Garlic', isFruit: false, id: 2 },
  { title: 'Apple', isFruit: true, id: 3 },
];

export default function ShoppingList() {
  
  //Create variable which contains result of array implementations into html
  const listItems = products.map(product =>
    <li
      key={product.id}
      style={{
        color: product.isFruit ? 'magenta' : 'darkgreen'
      }}
    >
      {product.title}
    </li>
  );

  // Simply return result of mapping in listItems
  return (
    <ul>{listItems}</ul>
  );
}

Responding to HTML events
#

Simply write javascript function for html ‘onClick’ event.

Alert.jsx

function MyButton() {
  function handleClick() {
    alert('You clicked me!');
  }

  return (
    <button onClick={handleClick}> / *
      Click me
    </button>
  );
}

*Just put function name in html, react will find the function name

Updating the screen/state
#

Think of this like giving a react component memory.

Finally time to understand the dreaded...

useState()!!!!

Not all components come baked with memory. Think of the difference between combinational vs sequential circuits from computer design & assembly. Components without state are like combinational circuits, no idea of state/memory as it is not always needed. However, ‘useState’ introducts persistent memory to the component, turning it into a sequential circuit, if that helps. Now, current state is depended on both the inputs and it’s previous state.

This added complexity is necessary, however is likely the pitfall as to why I haven’t been able to understand the code before this. Tools like HTMX helped me run from the problem, by forcing the front end to simply render the data, of which the backend handled all of. All logic as to state and whatnot would be handled on the host server, meaning any update to state in HTMX would require an web request, which can ultimately be detrimental when scaling up large applications.

Thus, React helps to push some of that logic onto the client’s computer at the cost of computer memory and possible performance. However, I think it will lead to a better overall understanding of the codebase as opposed to HTMX inthe long run. But we will have to see if that is the case.

Now, back to the docs.

Because components don’t require state, you will need to import the useState functionality at the beginning of your component using the following line.

import { useState } from 'react'; // *

*This format will be used in the future to implement more react features.

Here is a counter using useState():

Counter.jsx

export default function MyButton() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <button onClick={handleClick}>
      Clicked {count} times
    </button>
  );
}

App.jsx

export default function MyApp() {
  return (
    <div>
      <h1>Counters that update separately</h1>
      // Both the following buttons will have 
      // an independent state
      <MyButton />
      <MyButton />
    </div>
  );
}

State Hooks
#

React hooks allow for data to be shared among multiple components. Think of it like global variables in python to C++. Rather than components tracking their own state, they simply present the App’s states.

Steps:

  1. Move state logic from component to root app component
export default function MyApp() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <h1>Counters that update separately</h1>
      <MyButton />
      <MyButton />
    </div>
  );
}

function MyButton() {
  // ... we're moving code from here ...
}
  1. Pass state and event handlers (onClick function) as attributes to html element.
export default function MyApp() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <h1>Counters that update together</h1>
      <MyButton count={count} onClick={handleClick} />
      <MyButton count={count} onClick={handleClick} />
    </div>
  );
}
  1. Simply pass attributes to button and now you have the data needed to present your data in HTML elements.
function MyButton({ count, onClick }) {
  return (
    <button onClick={onClick}>
      Clicked {count} times
    </button>
  );
}

That’s all for now. Gonna have to get my hands dirty to learn more. Already had my first issues while trying to make an editable post component right after doing this. Here’s to more learning this summer!🎊

Development
abdiToldSo
Author
abdiToldSo
Computer Science Undergrad @ UMBC

Related

The Beginning
·507 words·3 mins
Development
Welcome to A2T, my Personal Blog!
Ableton for Beginners
·176 words·1 min
Personal Music
Introductory lesson given to the UMBC Retriever Music Society
Resume
·6 words·1 min
Professional Resume
For recruiters, spies, and the curious.