Sunday, August 1, 2021

React's useState hook

Let's test React's useState hook (please note these can only be used inside higher level functions and also, not inside conditionals)

import { array } from 'prop-types';
import React, { useState } from 'react';

function App3() {
  const useStateTest = useState("user");
  console.log(useStateTest);
  return (
    <h1>hello</h1>
  );
}

export default App3;

Console will print the following:

Array [ "user", dispatchAction() ]
0: "user"
1: function dispatchAction()
length: 2

As you can see in the array, this hook prints the "user" string in the first space followed by a function. This function is the one that lets you update the value of the first space within the array (kind of like a bridge).

Now, let's use an array deconstruct to just print the first item within the array to go next to our h1 element:

function App3() {
  const [useStateTest] = useState("user");

  return (
    <>
      <h1>hello {useStateTest}</h1>
    </>
  );
}

This time, your app will show the following in the browser:

hello user

Now let's change such string (or state variable) by making use of the useState hook in a button element:

First, we need to add our own custom name to the useState function (dispatchAction) which uses the second space within the array. By convention, the "set" prefix is always used here. So, we'll name it "setUserName" (please note that the variable within this function should not be limited to strings, it can also be numbers or booleans).

Next, we add the button into our app along with the onClick action handler which contains our custom setUserName useState function where we specify the new name to be displayed:

function App3() {
  const [useStateTest, setUserName] = useState("user");

  return (
    <h1>hello {useStateTest}</h1>
<button onClick={() => setUserName("Username")}>
Username
</button> ); }

Once you save, you'll see the same/previous heading + our new button

If you click the button, the string "user" will now change to "Username":

hello Username

..and that's it :)

Thursday, July 29, 2021

Destructure arrays and objects

Typically, to show specific items within an array, you’d use the array name followed by its key number:

const myArray = ["item1", "item2", "item3"];
console.log(myArray[2]);

This will print: item3

Sometimes though some devs may find it useful to work with variable names instead of key numbers:

const [,,myItem3] = ["item1", "item2", "item3"];
console.log(myItem3);

This will also print: item3

You may also find this in app components that have multiple property names (object keys):

function App2(props) {
  return (
    <>
      <h1>{(props.title)}</h1>
      {(props.access) ? <GrantAccessMessage /> : <DeniedAccessMessage />};
    </>
  )
}

export default App2;

Typical function uses the props object + property name (or object key):

The deconstructed one only uses property names:

function App2({title, access}) {
  return (
    <>
      <h1>{(title)}</h1>
      {(access) ? <GrantAccessMessage /> : <DeniedAccessMessage />};
    </>
  )
}

export default App2;

Monday, July 26, 2021

Quick example on how to do conditionals in React

Here's a quick example on how to do conditionals in React

First, you create a component for each condition in your app (called App2 in this example):

function GrantAccessMessage() {
  return <h2>Access Granted!</h2>
}
function DeniedAccessMessage() {
  return <h2>Access Denied!</h2>
}

Next, call both components inside your app component by using shorthand/ternary conditional statement. This has to be wrapped inside brackets.

Please note we'll be adding a manual true/false value to the "access" component attribute in our index.js file

function App2(props) {
  return (
    <>
{(props.access) ? <GrantAccessMessage /> : <DeniedAccessMessage />};
</> ) }

Now, export your app:

export default App2;

Add a manual true/false value to the "access" component attribute in our index.js file

import App2 from './App2';

ReactDOM.render(
  <App2 access={false} />,
  document.getElementById('root')
);

That's it!

Saturday, July 24, 2021

Parse error: Adjacent JSX elements must be wrapped in an enclosing tag

 React will not let you render two adjacent components unless you wrap them inside a div. This has a downside: your app may contain a lot of wrapping divs.

ReactDOM.render(
  <div>
<App1 />
<App2 />
</div>, document.getElementById('root') );

To avoid this issue, you can make use of the short syntax of the Fragments API which is included in React. 

ReactDOM.render(
  <>
<App1 />
<App2 />
</>, document.getElementById('root') );

That's it! no more dirty markup nor error messages :)

Friday, July 16, 2021

Component code snippets

 Here’s a handful of helpful React component code snippets:

 Simple variable usage:

function Header(props) {
  return (
    <header>
<h1>{props.pageType2} not found</h1>
</header> ) } function App() { return ( <div className="App">
<Header pageType2="Website" />
</div> ); } export default App;

 Variable usage with values taken from array object (using map function for looping):

    function Main(props) {
        return (
          <main>
<h2>Try using a different {props.solution}</h2>
<ul>
{props.userOptions.map((userOption)=><li key={userOption.id}>{userOption.title}</li>)}
</ul>
</main> ) } const userOptions = [ "Try a different wording", "Go back to homepage", "Try different keywords" ]; const userOptionsObject = userOptions.map((userOption, i) => ({ id: i, title: userOption })); function App() { return ( <div className="App">
<Main solution="address" userOptions={userOptionsObject}/>
</div> ); } export default App;

Inline CSS styles

  function RandomParagraph() {
    return (
      <section>
<p style={{ textAlign: "left" }}></p>
</section> ); }
Please note inline styles are not recommended, for more details, see: https://reactjs.org/docs/dom-elements.html#style

Component basics (App.js)

To render HTML elements, we create components (js functions) inside the app file.

This is the basic structure:

Import styles:

import './App.css'; 

Here's a basic component (as u can see, it's using XML markup)

function Header() {
  return (
    <h1>Here's my title without variables</h1>
  )
} 

Here's another component but this time we use a variable (defined in component) called contentText which has to be used with React's default object named props

function Content(props) {
  return (
    <p>This is my content added via custom variable: {props.contentText}</p>
  )
}

This is all added to the component called App as individual objects (where values are added to the variables which are included in the form of component/object attributes): 

function App() {
  return (
    <div className="App">
<Header />
<Content contentText="added via object attribute!" />
</div> ); }

This is all exported so it can be used as object in the main app (index.js)

export default App;

Sunday, July 11, 2021

Initiate a project in React (using create-react-app)

 1- In your terminal, make sure you have node and npm installed

for node:

node -v

for npm:

npm -v


2- Create the "bare bones" project by using:

npx create-react-app my-custom-project

where: my-custom-project is your project's name


3- Here’s the purpose of each file:

index.js pulls all pieces together: from all the different js files or "components" you've created and inserts/injects them into the specified element (#root by default)

ReactDOM.render(
<App />,
document.getElementById('root')
);

App.js is the default/sample "component" which is imported into index.js by using

import App from './App';