React — Tips & Tricks

📄 Table of contents

◉ how to pass props from PARENT to CHILD in Class vs Functional components

In React, props stand for “properties” and they are the way we pass data from one React component to another.

React’s props are read-only. There is no way in React to set props (even though it was possible in the past).

However, Once the state changes, the component renders again. In addition, state can be passed as props to child components too.

Props are passed as arguments into a React component. The syntax for passing props is the same for class and functional components, but the syntax for accessing these props is different.

props can be anything from integers over objects to arrays. Even React components, but you will learn about this later. You can also define the props inline. In case of strings, you can pass props inside double quotes (or single quotes) too.

But you can also pass other data structures with inline props. In case of objects, it can be confusing for React beginners, because you have two curly braces: one for the JSX and one for the object. That’s especially confusing when passing a style object to a style attribute in React the first time.

import React, { Component } from 'react';class App extends Component {
render() {
return (
<div>
<Greeting greeting={{ text: 'Welcome to React' }} />
</div>
);
}
}
const Greeting = ({ greeting }) => <h1>{greeting.text}</h1>;export default App;

Where class and functional components differ is in accessing props. In a functional component, you will see the props object as a parameter and can access it without the this keyword. It is also best practice to destructure the object using the destructuring assignment syntax to make it clear what props you are expecting in the component.

function App() {
const blogPost = {
title: 'How to pass prop to components',
description: 'Your component library for ...',
};
return (
<div>
<BlogCard
title
={blogPost.title}
description={blogPost.description} />
</div>
);
}

function BlogCard({ title, description }) {
return (
<div>
<h1>{title}</h1>
<p>{description}</p>
</div>
);
}

more at @source: How to pass props in React (koalatea.io)

Basically, that’s how props are passed to React components.

As you may have noticed, props are only passed from top to bottom in React’s component tree. There is NO way to pass props up to a parent component.

In conclusion, every time the props or state change, the rendering mechanism of the affected component is triggered. That’s how the whole component tree becomes interactive, because after all, state is passed as props to other components, and once the state in a component changes, which may be passed as props to the child components, all affected components render again.

Passing a function as a prop to a functional component

The first parameter logThis will be props object itself. You need to destructure the logThis object.

const ChildComp = ({ logThis }) => (
<button onClick={() => logThis('test string')}>Click Here</button>
)

Or you can access it from props

const ChildComp = (props) => (
<button onClick={() => props.logThis('test string')}>Click Here</button>
)

◉ Sending props as strings (instead of numbers)

React developers with experience writing a lot of HTML find it natural to write something like this:

<MyComponent value=”4” />

This value prop will actually be sent to MyComponent as a string. If you do need it as a number, you can fix this issue by using something like the parseInt() function or inserting curly brackets instead of quotation marks.

<MyComponent value={4} />

React — How to force a function component to render?

I have a function component, and I want to force it to re-render.

How can I do so?
Since there’s no instance this, I cannot call this.forceUpdate().

🎉 You can now, using React hooks

Using react hooks, you can now call useState() in your function component.

useState() will return an array of 2 things:

  1. A value, representing the current state.
  2. Its setter. Use it to update the value.

Updating the value by its setter will force your function component to re-render,
just like forceUpdate does:

◉ Prop validation

Since, Javascript is not a TYPED language there is a helpful package to validate the prop types passed into a React component, which will help when reading and debugging code.

This package is called prop-types.

Here is an example of using prop-types to validate our props.

import PropTypes from 'prop-types';function BlogCard({ title, description }) {
return (
<div>
<h1>{title}</h1>
<p>{description}</p>
</div>
);
}
BlogCard.propTypes = {
title: PropTypes.string,
description: PropTypes.string,
};

◉ difference between import {sthg…} vs import sthg…

when you are doing export default <sthg> then while DON’T include {}while importing the same.

When you have to export multiple <sthg> <sthg1> then don’t include default keyword…simply export const <sthg> <sthg1>. but while importing you will have to include {}

Both lines are equivalent.

◉ template literal usage

console.log(`Using video device: ${videoTracks[0].label}`);console.log("Using video device: " + videoTracks[0].label);

◉ delete remote branch on git

@https://www.makeuseof.com/how-to-delete-branch-git/

Deleting a remote branch is quite different. You’ll use the git push command along with the -d flag to delete. After that, supply the name of the remote (often origin) and the branch name:

$ git push -d origin dev
To github.com:bobbykjack/sandbox.git
- [deleted] dev

◉ useState on array

@ https://daveceddia.com/usestate-hook-examples/

const [optionsList, setOptionsList] = useState(["default"]);setOptionsList([...optionsList, `${videoTracks[0].label}`]);

◉ How to submit form data in React

Ref: How to submit form data in React (sebhastian.com)

<form onSubmit={handleSubmit}>
<div>
<label>Email address</label>
<input
type="email"
name="email"
placeholder="Enter email"
onChange={handleEmailChange}
value={email}
/>
</div>
<button type="submit">
Submit
</button>
</form>

you need to cancel the form submission default behavior with preventDefault() while submitting the form via handleSubmit here.

◉ Handling Multiple Inputs with a Single onChange Handler in React

Ref: Handling Multiple Inputs with a Single onChange Handler in React | Pluralsight

Besides handling just one input, a single onChange handler can be set up to handle many different inputs in the form.

Logic: To handle this efficiently, we define each input with a name prop. This matches a corresponding field in React state. In order to update that state, we use the change event’s evt.target.name field.

In addition to getting the value from the event target, we get the name of that target as well. This is the essential point for handling multiple input fields with one handler. We funnel all changes through that one handler but then distinguish which input the change is coming from using the name.

This example is using [evt.target.name], with the name in square brackets, to create a dynamic key name in the object. Because the form name props match the state property keys, the firstName input will set the firstName state and the lastName input will separately set the lastName state.

Also note that, because we are using a single state object that contains multiple properties, we're spreading (...state) the existing state back into the new state value, merging it manually, when calling setState. This is required when using React.useState in the solution.

◉ handle multiple setStates in consecutive

It’s easy to forget that the state in React is asynchronous. It’s something that even the most seasoned React developers forget.

Being asynchronous means that any modifications you make don’t take effect immediately (and may take effect on the next render). React automatically batches update calls to improve performance. If you access a state value right after setting it, you might not get the most accurate result.

Let’s look at an example:

handlePetsUpdate = (petCount) => {
this.setState({ petCount });
this.props.callback(this.state.petCount); // Old value
};

You can fix this by giving an optional second parameter to setState(), which will act as a callback function. The callback function will be called right after you update the state with your change.

handlePetsUpdate = (petCount) => {
this.setState({ petCount }, () => {
this.props.callback(this.state.petCount); // Updated value
});
};

Note: The same thing is true for useState(), except they don’t have a similar callback argument to setState(). Instead, you would use the useEffect() hook to get the same result.

◉ Add Required (*) using CSS on dynamic form data

Ref: Add Required Asterisk With CSS — Paulund

But what would happen if you forget to add the asterisk after a form field or if the form is dynamically created, here is a quick tip for automatically adding a red asterisk next to required fields just by using CSS. Here is a standard HTML for creating a form field as you can see the label has a required class therefore we need to add an asterisk after this label.

<div class="form-group">
<label class="control-label required" for="username">Username</label>
<input type="text" id="username" name="data[username]" required="required" class="form-control">
</div>

Using CSS we search for all labels with a class required and use the :after pseudo class to add an asterisk and set the colour to red.

form label.required:after
{
color: red;
content: " *";
}

◉ Toggle a ClassName — the Hooks way

Ref: https://reactgo.com/react-toggle-class/

Toggle between two classnames

return (
<div className={isActive ? "app" : "container"}>
...
)

Adding a classname to the existing class name

return (
<div className={`app ${isActive ? "danger" : ""}`}>
...
)

fetch data from APIs with Axios and Hooks

Ref: How to fetch data from APIs with Axios and Hooks in React — Kindacode

multiple option selection in react select

Ref: https://stackoverflow.com/questions/28624763/retrieving-value-from-select-with-multiple-option-in-react

Form Validations

Ref: http://jsfiddle.net/5e6zr2Lq/1/

◉ How To Format Code with Prettier in Visual Studio Code

Do we need to import React for stateless functional components?

Basically, no. In the past, you had to import it but with the new React 17 update , you don’t need to import React .

Further information at : react official blog , stackoverflow

What is the index.js file in the component directories?

You may have seen a folder structure like this before :

Why we use index.js here? When we need to import a component, we could’ve done it by directly importing component.

We use index.js, because inside index.js, we can do something like this:

And when we want to import our components, we can use a syntax like this:

import {CartProduct} from './Components/Cart'

instead of

import {CartProduct} from './Components/Cart/CartProduct'

That’s because when we import a file from a directory, it tries to access index.js file by default . Basically it’s a refactoring technique to keep code simpler.

Further read: stackoverflow

Event handlers must always be a function or a reference to a function (with an exception) .

Many people often get confused on about how to use event handlers.

In the below example;

2nd and 3rd buttons won’t work because instead of passing a function or function reference, we’re passing function calls. React calls them on first render, doesn’t wait for buttons to be clicked.

But,

In the 1st example, we are passing a function reference, and in the 4th example, we’re passing a function (literally). Thus , these both work correctly.

But , there’s an exception here. Which are the functions that return functions.

Now, each button has their own handler, this is a cool trick.

--

--

--

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

A More Streamlined Way To Change Styles on Your HTML nodes

Role-Based Access Like a Pro

Role-Based Access Like a Pro Article

Tricky JavaScript: Part-2

VS Code setup for front-end development

6 Best Practices for Building React Native Applications

Creating a cheap high-availability deployment for Meteor

🕹️How to use a Joystick & Arduino to control a mouse cursor with NodeJS

React-Native Firebase Phone Authentication with CRUD Operations and Image Upload on storage.

React-Native Firebase Phone Authentication with CRUD Operations and Image Upload on storage

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Anil Kumar

Anil Kumar

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

More from Medium

How To Create and Set Up a React Project with Create React App in Windows?

Input Validation in React Hook Form & sending emails using EmailJS in ReactJS

How to use the color picker in ReactJS

Some Changes in React Router v6