Categories
JavaScript Answers

How to fix function being called twice in React?

To fix function being called twice in React, we disable strict mode.

For instance, if we have

<React.StrictMode>
  <App />
</React.StrictMode>

then we disable strict mode by removing the React.StrictMode component from the code.

Categories
JavaScript Answers

How to convert milliseconds to hours and minutes using Moment.js and JavaScript?

To convert milliseconds to hours and minutes using Moment.js and JavaScript, we use the duration method.

For instance, we write

const x = 433276000;
const tempTime = moment.duration(x);
const hours = tempTime.hours();
const minutes = tempTime.minutes();

to call duration with the number of milliseconds to convert it to a duration object.

Then we call hours to get the number of hours and minutes to get the number of minutes.

Categories
React Answers

How to highlight text using React?

To highlight text using React, we can use the react-highlighter module.

To install it, we run

npm i react-highlighter

Then we write

const Highlight = require("react-highlighter");

<Highlight search="brown">
  The quick brown fox jumps over the lazy dog
</Highlight>

to use the Highlight component to highlight 'brown' in 'The quick brown fox jumps over the lazy dog'.

Categories
JavaScript Answers

How to enable CORS in production with Nest.js?

To enable CORS in production with Nest.js, we call the enableCors method.

For instance, we write

const app = await NestFactory.create(ApplicationModule);
app.enableCors();
await app.listen(3000);

to call create to create a Nest.js app.

Then we call enableCors to enable CORS on the app.

Categories
JavaScript Answers

How to add a time delayed redirect with JavaScript?

To add a time delayed redirect with JavaScript, we call setTimeout.

For instance, we write

setTimeout(() => {
  window.location.href = "/blog";
}, 2000);

to call setTimeout with a callback to redirect to the /blog page after 2000 milliseconds.