React conditionally render based on viewport size

Perhaps I am suppposed to work it with ComponentWillMount or ComponentDidMount Yes, you need to listen for resize event and update internal state on change. You can do it by adding event handler when component mounts. Try full example here. class App extends React.Component { constructor(props) { super(props); this.state = { isDesktop: false //This is …

Read more

How do I change the background color of the body?

The simplest solution is a bit hacky, but you can use raw javascript to modify the body style: document.body.style=”background: red;”; // Or with CSS document.body.classList.add(‘background-red’); A cleaner solution could be to use a head manager like react-helmet or next.js Head component. import React from ‘react’; import {Helmet} from ‘react-helmet’; class Application extends React.Component { render …

Read more

Toast is not rendered (react-toastify component)

You have to also import ‘react-toastify/dist/ReactToastify.css’; import React, { Component } from ‘react’; import { ToastContainer, toast } from ‘react-toastify’; import ‘react-toastify/dist/ReactToastify.css’; // minified version is also included // import ‘react-toastify/dist/ReactToastify.min.css’; class App extends Component { notify = () => toast(“Wow so easy !”); render(){ return ( <div> <button onClick={this.notify}>Notify !</button> <ToastContainer /> </div> ); …

Read more

useState vs useReducer

useReducer also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks. The above statement is not trying to indicate that the setter returned by useState is being created newly on each update or render. What it means is that when you have a complex logic …

Read more

Declaring Const With Curly Braces in JSX

It is destructuring assignment. The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. Example (ES6): var person = {firstname: ‘john’, lastname: ‘doe’}; const firstname = person.firstname; const lastname = person.lastname; // same as this const { firstname, lastname } = …

Read more