Categories
React Answers

How to Detect When a User Scrolls to Bottom of div with React?

Sometimes, we want to detect when a user scrolls to bottom of div with React.

In this article, we’ll look at how to detect when a user scrolls to bottom of div with React.

Detect When a User Scrolls to Bottom of div with React

To detect when a user scrolls to bottom of div with React, we can check if the sum of the scrollTop and clientHeight properties of a scrollable element is equal to the scrollHeight property of the same element.

For instance, we write:

import React, { useRef } from "react";

export default function App() {
  const listInnerRef = useRef();

  const onScroll = () => {
    if (listInnerRef.current) {
      const { scrollTop, scrollHeight, clientHeight } = listInnerRef.current;
      if (scrollTop + clientHeight === scrollHeight) {
        console.log("reached bottom");
      }
    }
  };

  return (
    <div>
      <div
        onScroll={onScroll}
        ref={listInnerRef}
        style={{ height: "200px", overflowY: "auto" }}
      >
        {Array(200)
          .fill()
          .map((_, i) => {
            return <p key={i}>{i}</p>;
          })}
      </div>
    </div>
  );
}

We call the useRef hook to create a ref and we assign the returned ref to the inner div, which is scrollable.

Then we define the onScroll function that destructures the scrollTop, clientHeight and scrollHeight properties from the scrollable div.

The scrollable div element is stored in listInnerRef.current since we assigned the ref to it.

Then we add an if statement to compare scrollTop + clientHeight to scollHeight.

We make the div scrollable by setting it to a fixed height and set overflowY to 'auto'.

And we set the onScroll prop to onScroll so the onScroll function runs when we scroll the scrollable div.

If they’re the same, then we know we reached the bottom.

Therefore, if we scroll to the bottom of the scrollable div, we should see 'reached bottom' logged.

Conclusion

To detect when a user scrolls to bottom of div with React, we can check if the sum of the scrollTop and clientHeight properties of a scrollable element is equal to the scrollHeight property of the same element.

Categories
React Answers

How to Set HTML body Element Styles from within a React Component?

Sometimes, we want to set HTML body element styles from within a React component.

In this article, we’ll look at how to set HTML body element styles from within a React component.

Set HTML body Element Styles from within a React Component

To set HTML body element styles from within a React component, we can set the document.body.style properties to the values we want.

For instance, we write:

import React, { useEffect } from "react";

export default function App() {
  useEffect(() => {
    document.body.style.backgroundColor = "yellow";

    return () => {
      document.body.style.backgroundColor = "white";
    };
  }, []);
  return <div>hello world</div>;
}

We set document.body.style.backgroundColor to the value we want in the useEffect hook so that it’s set to the value we want when the component is rendered.

And we set the 2nd argument of the hook to an empty array so that the background color is only set when the component is first rendered.

Also, we return a function that sets the background color when we unmount the component in the useEffect callback.

Now we should see the page has a yellow background.

Conclusion

To set HTML body element styles from within a React component, we can set the document.body.style properties to the values we want.

Categories
React Answers

How to Transfer All Props Except One to a React Component?

Sometimes, we want to transfer all props except one to a React component.

In this article, we’ll look at how to transfer all props except one to a React component.

Transfer All Props Except One to a React Component

To transfer all props except one to a React component, we can destructure the properties we want to pass into the child component with the rest syntax.

For instance, we write:

import React from "react";

const Foo = (props) => {
  return <div>{JSON.stringify(props)}</div>;
};

export default function App() {
  const props = { foo: 1, bar: 2, baz: 3 };
  const { foo, ...restProps } = props;

  return <Foo {...restProps} />;
}

We have a Foo component that renders the props object.

In App, we have the props object with some properties we want to pass to Foo as props.

We want to pass everything except the foo property.

To do this, we destructure props and put all properties except foo into the restProps object.

Then we pass the properties in restProps into Foo with the destructuring syntax.

Therefore, we should see {"bar":2,"baz":3} rendered.

Conclusion

To transfer all props except one to a React component, we can destructure the properties we want to pass into the child component with the rest syntax.

Categories
React Answers

How to Validate Input Values with React?

Sometimes, we want to validate input values with React.

In this article, we’ll look at how to validate input values with React.

Validate Input Values with React

To validate input values with React, we can use the react-hook-form library.

To install it, we run:

npm i react-hook-form

Then we can use it by writing:

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors }
  } = useForm();
  const onSubmit = (data) => console.log(data);

  console.log(watch("name"));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input defaultValue="jane" {...register("firstName")} />
      <input {...register("lastName", { required: true })} />
      {errors.lastName && <span>This field is required</span>}

      <input type="submit" />
    </form>
  );
}

We call the useForm hook to return an object with various properties.

And we use the register function to register the fields so that react-hook-form can do validation on the field.

We pass in the name of the field and an object with the validation options of the field.

To make a field required, we set the required property to true.

Then we can show the errors from the errors object.

The onSubmit function is the function that runs when the form values are all valid.

We call handleSubmit with onSubmit so that it only runs when the form values are valid.

handleSubmit returns a function that we can use as the event handler for the submit event of a form.

Now when we click Submit without the lastName field filled out, we should see an error message displayed.

Conclusion

To validate input values with React, we can use the react-hook-form library.

Categories
React Answers

How to Render React Components with Promises Inside?

Sometimes, we want to render React components with promises inside.

In this article, we’ll look at how to render React components with promises inside.

Render React Components with Promises Inside

To render React components with promises inside, we can use the usePromise hook provided by the react-promise package.

To install it, we run:

npm i react-promise

Then we can use it by writing:

import React from "react";
import usePromise from "react-promise";

export default function App() {
  const { value, loading } = usePromise(Promise.resolve("hello world"));
  if (loading) {
    return null;
  }
  return <div>{value}</div>;
}

We call usePromise with a promise that resolves to 'hello world'.

It returns an object with the value and loading properties.

value is the resolved value of the promise.

loading is a boolean that indicates whether the promise is loading or not.

Conclusion

To render React components with promises inside, we can use the usePromise hook provided by the react-promise package.