Categories
React Answers

How to Set State Inside a React useEffect Hook Callback?

Sometimes, we want to set states inside the React useEffect hook callback.

In this article, we’ll look at how to set states inside the React useEffect hook callback.

Set State Inside a useEffect Hook

We can set state inside the useEffect hook by merging the values of the existing state with the new values and returning that as the state in the state updater function.

For instance, we write:

useEffect(() => {
  setState(state => ({ ...state, foo: props.foo }));
}, [props.foo]);

useEffect(() => {
  setState(state => ({ ...state, bar: props.bar }));
}, [props.bar]);

We watch the props properties by passing them into the array.

Then we merge the items into the state object that we return in the callback.

Conclusion

We can set state inside the useEffect hook by merging the values of the existing state with the new values and returning that as the state in the state updater function.

Categories
React Answers

How to Set Body Styles with React?

Sometimes, we want to set body styles within our React app.

In this article, we’ll look at how to set body styles within our React app.

Set Body Styles with React

Within our React component, we can set the body style with plain JavaScript.

For instance, we can write:

componentDidMount(){
  document.body.style.backgroundColor = "green";
}

componentWillUnmount(){
  document.body.style.backgroundColor = null;
}

We set the document.body.style.backgroundColor property to set the background color.

componentDidMount lets us run code when the component mounts.

componentWillUnmount runs when the component unmounts.

Conclusion

Within our React component, we can set the body style with plain JavaScript.

Categories
React Answers

How to Create a Modal in a React App?

We can use React’s portal feature to render our component anywhere.

This way, we can create a modal that’s attached to whatever element we want.

For instance, we can write:

const ModalComponent = ({ children, onClose }) => {
  return createPortal(
    <div className="modal" onClick={onClose}>
      {children}
    </div>,
    document.getElementById("portal")
  );
};

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      showModal: false
    };
  }

  render() {
    return (
      <div>
        <button onClick={() => this.setState({ showModal: true })}>
          Open modal
        </button>
        {this.state.modalOpen && (
          <ModalComponent onClose={() => this.setState({ showModal: false })}>
            <h1>modal content</h1>
          </ModalComponent>
        )}
      </div>
    );
  }
}

We create a ModalComponent component to let us nest content inside it.

We can do that since it takes the children component.

All we have to do is render the children prop.

We use React’s createPortal method to let us render the div anywhere we want.

In App , we created a button to let us open the modal.

To do that, we set the showModal state to true .

We also created a function that we pass into the onClose prop of ModalComponent so that showModal can be set to false .

This will close the modal since ModalComponent is only shown when showModal is true .

Categories
JavaScript Answers

How to Convert a Floating-Point Number to a Whole Number in JavaScript?

Converting a floating-point number to a whole number is something that we’ve to do sometimes in JavaScript apps.

In this article, we’ll look at how to convert a JavaScript floating-point number to a whole number.

Math.floor

The Math.floor method lets us round a number down to the nearest integer.

For instance, we can use it by writing:

const intvalue = Math.floor(123.45);  
console.log(intvalue)

Then we get 123 as the value of intValue .

Math.ceil

The Math.ceil method lets us round a number up to the nearest integer.

For instance, we can write:

const intvalue = Math.ceil(123.45);  
console.log(intvalue)

Then intValue is 124.

Math.round

The Math.round method lets us round a number down to the nearest integer if the first decimal digit is 4 or lower.

Otherwise, it rounds the number up to the nearest integer.

For instance, if we have:

const intvalue = Math.round(123.45);  
console.log(intvalue)

Then intValue is 123.

Math.trunc

The Math.trunc method lets us return the integer part of a number by removing the fractional digits.

For example, we can write:

const intvalue = Math.trunc(123.45);  
console.log(intvalue)

Then intValue is 123.

parseInt

The parseInt function lets us convert a floating-point number to an integer.

It works like Math.trunc in that it removes the fractional digits from the returned number.

For example, we can write:

const intvalue = parseInt(123.45);  
console.log(intvalue)

And intValue is 123.

To make sure that we return a decimal number, we pass 10 into the 2nd argument:

const intvalue = parseInt(123.45, 10);  
console.log(intvalue)

Conclusion

JavaScript provides a few functions and methods to lets us convert floating-point numbers to integers.

Categories
JavaScript Answers

How to Get the Name of a JavaScript Object’s Type?

Getting the name of the constructor that an object is created from is something that we’ve to sometimes.

In this article, we’ll look at how to get the name of the constructor that the JavaScript object is created from.

The constructor Property

We can use the constructor property of an object to get the constructor that it’s created from.

For instance, we can write:

const arr = [1, 2, 3];
console.log(arr.constructor === Array);

Then the console log logs true since the arr is created with the Array constructor.

This can also be used with constructors we create ourselves:

class A {}
const a = new A()
console.log(a.constructor === A);

The console log will also log true .

Inheritance

If we create an object from a subclass, then we can check if an object created from the current subclass.

For instance, we can write:

class A {}
class B extends A {}
const b = new B()
console.log(b.constructor === B);

Then the console log also logs true since b is created from the B constructor.

constructor has the name property to get the constructor name as a string.

For instance, we can write:

class A {}
const a = new A()
console.log(a.constructor.name === 'A');

to compare against the name of the constructor.

The instanceof Operator

The instanceof operator also lets us check if an object is created from a constructor.

For instance, we can write:

const arr = [1, 2, 3];
console.log(arr instanceof Array);

Then the console log should log true since arr is an array.

However, the Array.isArray is more reliable for checking if a variable is an array since it works across all frames.

Also, we can write:

class A {}
const a = new A()
console.log(a instanceof A);

to check if a is an instance of A .

instanceof also works with subclasses.

So we can write:

class A {}
class B extends A {}
const b = new B()
console.log(b instanceof B);

And it’ll log true .

Conclusion

We can use the instanceof operator and the constructor property to check if an object is created from the given constructor.