Categories
React Answers

How to Add Swipe Effect in React?

Sometimes, we want to add Swipe effect in React.

In this article, we’ll look at how to add Swipe effect in React.

Add Swipe Effect in React

To add Swipe effect in React, we can add the onTouchStart on onTouchMove and onTouchEnd props and set them to event handler functions.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <div>
      <div
        onTouchStart={(touchStartEvent) => console.log(touchStartEvent)}
        onTouchMove={(touchMoveEvent) => console.log(touchMoveEvent)}
        onTouchEnd={() => console.log("onTouchEnd")}
        onMouseDown={(mouseDownEvent) => console.log(mouseDownEvent)}
        onMouseMove={(mouseMoveEvent) => console.log(mouseMoveEvent)}
        onMouseUp={() => console.log("onMouseUp")}
        onMouseLeave={() => console.log("onMouseLeave")}
      >
        swipe
      </div>
    </div>
  );
}

to add them.

The onTouchStart handler will run when we start swiping.

onTouchMove will run when we’re swiping.

onTouchEnd will run when we’re done swiping.

We also add mouse event handlers for compatibility with non-touch devices.

Conclusion

To add Swipe effect in React, we can add the onTouchStart on onTouchMove and onTouchEnd props and set them to event handler functions.

Categories
React Answers

How to Prevent Basic React Form Submit From Refreshing the Entire Page?

Sometimes, we want to prevent basic React form submit from refreshing the entire page.

In this article, we’ll look at how to prevent basic React form submit from refreshing the entire page.

Prevent Basic React Form Submit From Refreshing the Entire Page

To prevent basic React form submit from refreshing the entire page, we call e.preventDefault. in the submit event handler.

For instance, we write:

import React from "react";

export default function App() {
  const onSubmit = (e) => {
    e.preventDefault();
    console.log("refresh prevented");
  };

  return (
    <div>
      <form onSubmit={onSubmit}>
        <button type="submit">submit</button>
      </form>
    </div>
  );
}

to create the onSubmit function that’s set as the value of the onSubmit prop.

In the function, we call e.preventDefault to prevent the default submission behavior, which is to do server side form submission which refreshes the whole page.

We have a submit button in the form to do the form submission.

Therefore, instead of seeing the page refresh when we click submit, we should see the 'refresh prevented' string logged in the console instead.

Conclusion

To prevent basic React form submit from refreshing the entire page, we call e.preventDefault. in the submit event handler.

Categories
React Answers

How to Use the React setState Hook from Scroll Event Listener?

Sometimes, we want to use the React setState hook from scroll event listener.

In this article, we’ll look at how to use the React setState hook from scroll event listener.

Use the React setState Hook from Scroll Event Listener

To use the React setState hook from scroll event listener, we can call state setter functions from within in the scroll event handler.

For instance, we write:

import React, { useEffect, useRef, useState } from "react";

export default function App() {
  const prevScrollY = useRef(0);
  const [goingUp, setGoingUp] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      const currentScrollY = window.scrollY;
      if (prevScrollY.current < currentScrollY && goingUp) {
        setGoingUp(false);
      }
      if (prevScrollY.current > currentScrollY && !goingUp) {
        setGoingUp(true);
      }

      prevScrollY.current = currentScrollY;
      console.log(goingUp, currentScrollY);
    };

    window.addEventListener("scroll", handleScroll, { passive: true });

    return () => window.removeEventListener("scroll", handleScroll);
  }, [goingUp]);

  return (
    <div>
      {Array(200)
        .fill()
        .map((_, i) => (
          <p key={i}>{i}</p>
        ))}
    </div>
  );
}

We have the prevScrollY ref to store the previous scroll distance without trigger rerendering.

Then we define the goingUp state to set whether we’re scrolling up or down if it’s true or false respectively.

In the useEffect callback, we have the handleScroll function that gets the vertical scroll distance with window.scrollY.

And we compare that to prevScrollY.current to check if we’re scrolling up or down.

We set goingUp by calling setGoingUp in each case.

Then we set prevScrollY.current to currentScrollY after we did the comparison.

Finally, we log the scroll distance and the value of goingUp.

To use it as the scroll listener, we call window.addEventListener with it.

And we return a function that calls window.removeEventListener to remove the scroll listener when we unmount the component.

Now when we scroll up or down, we should see the the value of goingUp and the vertical scroll distance logged.

Conclusion

To use the React setState hook from scroll event listener, we can call state setter functions from within in the scroll event handler.

Categories
React Answers

How to Clear Browser Cache in React?

Sometimes, we want to clear browser cache in React.

In this article, we’ll look at how to clear browser cache in React.

Clear Browser Cache in React

To clear browser cache in React, we can add meta tags inside the head tag to make sure that the content of the page isn’t cached.

For instance, we put:

<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>

in the head tag to set the cache-control response reader to no-cache.

And the expires response header is set to 0 to make sure nothing is cached.

Conclusion

To clear browser cache in React, we can add meta tags inside the head tag to make sure that the content of the page isn’t cached.

Categories
React Answers

How to Write an else if Structure Using React JSX?

Sometimes, we want to write an else if structure using React JSX.

In this article, we’ll look at how to write an else if structure using React JSX.

Write an else if Structure Using React JSX

To write an else if structure using React JSX, we can write regular if-else statements in React components.

For instance, we write:

import React from "react";

const Condition = ({ conditionA, conditionB }) => {
  if (conditionA) {
    return <span>Condition A</span>;
  } else if (conditionB) {
    return <span>Condition B</span>;
  } else {
    return <span>Neither</span>;
  }
};

export default function App() {
  return (
    <>
      <Condition conditionA />
      <Condition conditionB />
      <Condition />
    </>
  );
}

to create the Condition component that takes the conditionA and conditionB props.

In the component, we check if conditionA is true, then we return a span with ‘Condition A’ as its content.

If conditionB is true, then we return a span with ‘Condition B’ as its content.

Otherwise, we return a span with ‘Neither’ as its content.

In App, we add Condition with the props.

Then we see:

Condition ACondition BNeither

displayed.

Conclusion

To write an else if structure using React JSX, we can write regular if-else statements in React components.