React — Tips & Tricks

📄 Table of contents

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

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

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)

<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?

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

🎉 You can now, using React hooks

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

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 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

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

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

◉ How to submit form data in React

<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

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

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

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

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

multiple option selection in react select

Form Validations

◉ How To Format Code with Prettier in Visual Studio Code

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