DEV Community

Cover image for ReactJS - Character Selection
Kyle A.
Kyle A.

Posted on

ReactJS - Character Selection

Test out: https://kylestech95.github.io/tile-selection-tool-interactive
Source Code: https://github.com/KylesTech95/tile-selection-tool-interactive
Clone Ref: https://github.com/KylesTech95/tile-selection-tool-interactive.git

As a gamer it is essential to navigate through options & characters. You can do exactly that with this traditional selection-feature created with ReactJS, CSS, & HTML.

Users can navigate through characters with their mouse or keypad:

Controls:

  • Mouse move/hover
  • > Right Arrow
  • < Left Arrow
  • v Down Arrow
  • ^ Up Arrow

Instructions

Instructions

Languages:

  1. ReactJS
  2. CSS
  3. JavaScript
  4. HTML

Learning Objectives from project-code

  1. Understanding of project setup
  2. Mapping data with key index
  3. Understanding a few basic ReactJS-Hooks:
  • a. useState()
  • d. useRef()

Project Setup

While there are a number of ways to setup a tile-selection program,
this project utilizes an array of objects, stored into a state called player, and then rendered into 6 list-items <li className="list-item"></li> in the domain(DOM).

character selection

Tile Tracking
Within App.js, take a look at the player Array.
Each object listed contains a src: property with an array of 2 numbers representing x & y, respectively.
After iterating through the array, each player src: is parsed into objects and used for tracking tiles in the DOM.

Within choice.js, un-comment the code below and press any arrow key to view the output:
// fn converts array to object with 2 arguments (element,index)
const arrayToObject = (p,index) =>{
return {x:p[index].pos[0],y:p[index].pos[1]}
}

const items = document.querySelectorAll('.list-item')

for(let i = 0; i < items.length; i++){
// convery array to an object
let obj = arrayToObject(player,i)
// console.log(obj)
// console.log(items[i])
// console.log("\n")
}

position coords

ReactJS Key

Stay on choice.js and navigate to // return render. Here,
player, or the array of objects, is being mapped to list all lite-items <li><li/> by its key property key={p.key}.
Typically a key is required if multiple objects/arrays within a list are being rendered.
The main purpose of keys is to determine which elements have been modified (modify,delete).
View the code below for a better understanding.

{[...player].map((p,index)=>{
return (
<div key={p.key} className="button-back">
<li key={p.key} className={
list-item p${index+1}}><img className="img" src={p.src} alt={p.alt} /></li>
</div>
)
})}

Test out: https://kylestech95.github.io/tile-selection-tool-interactive
Source Code: https://github.com/KylesTech95/tile-selection-tool-interactive
Clone Ref: https://github.com/KylesTech95/tile-selection-tool-interactive.git

hooks

Think of react hooks as an individual who is asthmatic & holds onto an inhaler to sustain life, or the life-cycle.

You, the developer have asthma and need to ensure your quality of life is functional.
Do I only have to use my inhaler? ... NO

In addition, you can:

  • Exercise to increase your stamina
  • Sustain a healthy diet
  • Sip on Tea Fennel Tea, Licorice Tea, Ginger Tea, etc...

Basically, whatever you need to do to maintain asthma may come in the form of the above bulletins.
Similarly, ReactJS uses hooks such as useState() and useRef.

useState Example
Within App.js, we declare a useState() with a string and store it in a variable called header.
Now we can use this state, or "life-sustainer" inside of a functional component

usestate1
Within the same file App.js scroll down to the bottom of the file.
Within the <Header/> component, plug in the header variable as a prop.
Just like the header prop, I carry my inhaler wherever I go to prevent asthma attacks or shortness of breath. I need to make living work!

usestate3
Within the same file, scroll to the top to access the Header
Component.
Plug your prop [header] into the function's arguments and pass it as text in the <h1> element.
At this point, we completed a quarter-mile jog.
But wait, in our current state we need to take our medicine[inhaler]! The welcome header is displayed.

usestate2
Within the same file App.js scroll down to the bottom of the file.
Within the <Choice/> component, plug in both header & setHeader variables as a prop.
usestate3
Access choice.js, navigate the Choice component. Plug-in both props [header & setHeader] into the function's arguments.

choiceusestate
Finally we set the header's state to the tile's animal-name by accessing it's alt property when we land on a tile.
Just like both header & setHeader props, after I use my inhaler[header] my breathing, or state changes. We then set the header to a different state with setHeader(). After arriving home, I drank ginger tea which changed my state again.
usestate5

For more information on useState() learn more with www3Schools

Test out: https://kylestech95.github.io/tile-selection-tool-interactive
Source Code: https://github.com/KylesTech95/tile-selection-tool-interactive
Clone Ref: https://github.com/KylesTech95/tile-selection-tool-interactive.git

useRef Example
The useRef() hook allows developers to reference elements that do not need to be rendered.

Imagine hiring a jewel-thief to access a secure diamond room by roping down from the roof. Despite evading all of security controls (trip-wires, lasers, cameras,automatic firearms,etc...), the thief keeps their cool. They tactfully grab the diamond and helicopter out from the roof!

The thief is your useRef() called thiefRef.
We hire the thief to change the state of the jewelryโ€™s position.
The state changes after the thief steals the diamond without crashing the application. We summoned our _ref
, the application's state changes and no one gets hurt or in trouble...unless you were the jeweler..

Since you hired the thief, and the job was successful, the thief is willing to rob more diamonds for you, in other words the theif,thiefRef can be reused without being rendered.

useRef in code
Scenario: I want to access the object {} at the top of the screen with the useRef() hook
object brack
Within App.js declare a useRef() and store it in a variable called posRef.
p1
Just like states, carry the posRef down to a component, in this case, we carry posRef down to the <Object/> component.
p2
Within the same file, scroll to the top of the page, locate the Object function, and plug-in posRef into the argument.
p3
Next, we plant our posRef into an html attribute called "ref".
p4

Finally, we access posRef with posRef.current which gives us access to the element where the id="object-container".
In the below code, we are removing the value's class, obj-remove with posRef.current. How cool is that!
removeobj
For more information on useRef() learn more with www3Schools

In conclusion,
working with the ReactJS Framework takes time and patience in order to understand how state works as well as the hooks that come with ReactJS.
May this blog post help broaden your understanding of the ReactJS Framework.

Test out: https://kylestech95.github.io/tile-selection-tool-interactive
Source Code: https://github.com/KylesTech95/tile-selection-tool-interactive
Clone Ref: https://github.com/KylesTech95/tile-selection-tool-interactive.git

Top comments (0)