admin管理员组

文章数量:1025203

I have a ponent A that renders once the application loads.

I am looking to render another ponent B the moment ponent A leaves
the screen. This happens when the user scrolls ponent A off screen.

And also when user scrolls ponent A back into the screen, ponent B should
disappear.

Looking for guidance on how I could track whether ponent A is on the screen or off screen in React.
Please advice.

Idea is below. Looking for a way to listen if ponent A is on screen or not and setShowB(false) or setShowB(true) accordingly.

import React, { useState } from 'react';

const AComponent = () => {
  const [showB, setShowB] = useState(false); // I do want this to be a boolean
  const setVisibility = (showB) => showB ? 'visible' : 'hidden'

  return (
    <div>

      <div id='A' style={{ visibility: setVisibility(showB)}}>
        I am ponent A
      </div>

      <div id='B'>
        I am ponent B
      </div>

    </div>
  );
};

export default AComponent;

Note: Not looking to use any external libraries.

On page load only Component A shows.

===================================================================

when ponent A is scrolled off screen ponent B shows up.

I have a ponent A that renders once the application loads.

I am looking to render another ponent B the moment ponent A leaves
the screen. This happens when the user scrolls ponent A off screen.

And also when user scrolls ponent A back into the screen, ponent B should
disappear.

Looking for guidance on how I could track whether ponent A is on the screen or off screen in React.
Please advice.

Idea is below. Looking for a way to listen if ponent A is on screen or not and setShowB(false) or setShowB(true) accordingly.

import React, { useState } from 'react';

const AComponent = () => {
  const [showB, setShowB] = useState(false); // I do want this to be a boolean
  const setVisibility = (showB) => showB ? 'visible' : 'hidden'

  return (
    <div>

      <div id='A' style={{ visibility: setVisibility(showB)}}>
        I am ponent A
      </div>

      <div id='B'>
        I am ponent B
      </div>

    </div>
  );
};

export default AComponent;

Note: Not looking to use any external libraries.

On page load only Component A shows.

===================================================================

when ponent A is scrolled off screen ponent B shows up.

Share Improve this question edited Jul 19, 2021 at 18:22 Fllappy asked Jul 19, 2021 at 17:39 FllappyFllappy 4015 silver badges14 bronze badges 15
  • Hello Mate ! I am trying to look for a React solution for you. As per the requirement, You are saying only 1 Component should be displayed at a time. When a user scrolls a particular Component , that particular ponent should be removed of the DOM and another should be shown up at its place. My question to scroll up to the height of the Component, we must have more content on the page so that we are able to scroll on the page. Could you share the design of what you want to achieve, so that I can try to e up with a solution. :) Thanks – Imran Rafiq Rather Commented Jul 19, 2021 at 18:13
  • I would like to connect with you friend for this particular scenario, because I am trying to create the exact scenario. If you wish we can do this together here. I do not have all the context :) – Imran Rafiq Rather Commented Jul 19, 2021 at 18:15
  • The scenario is going to be somewhat like this: codesandbox.io/s/help-friend-stackoverflow-x15jf – Imran Rafiq Rather Commented Jul 19, 2021 at 18:17
  • @Flappy: When you say "when ComponentA is scrolled off the screen", We can only scroll a Component when its height is greater than the ViewPort or we have more content below it. So that we can scroll. So, could you provide any design about what you wish to achieve. Is there more stuff below the ComponentA as it first loads. – Imran Rafiq Rather Commented Jul 19, 2021 at 18:23
  • @ImranRafiqRather Updated question if it it helps clarify. Component B is a Sticky Component always stays on the bottom. – Fllappy Commented Jul 19, 2021 at 18:23
 |  Show 10 more ments

4 Answers 4

Reset to default 1

You can try this solution and build on top of this as per your requirement. You need to use useEffect() Hook to put all your scrolling code and manage state accordingly. useEffect() is used to manage all the sideEffects and for user scrolling useEffect() is the best place to write our Logic.

CODESANDBOX: https://codesandbox.io/s/help-friend-stackoverflow-x15jf?file=/src/App.js

TOTAL COMPONENTS USED:

App.js

import "./styles.css";
import ComponentA from "./ponents/ComponentA";
import ComponentB from "./ponents/ComponentB";
import OtherComponent from "./ponents/OtherComponent";
import { useState, useEffect } from "react";

export default function App() {
  const [isAOpen, setIsAOpen] = useState(true);

  useEffect(() => {
    window.addEventListener("scroll", () => {
      // let ponentHeight = document.querySelector(".pA").clientHeight;
      let scrolled = window.scrollY;

      console.log(scrolled);

      if (scrolled >= 530) {
        setIsAOpen(false);
      } else if (scrolled <= 10) {
        setIsAOpen(true);
      }
    });

    return () => {
      window.removeEventListener("scroll", () => {
        // let ponentHeight = document.querySelector(".pA").clientHeight;
        let scrolled = window.scrollY;

        console.log(scrolled);

        if (scrolled >= 530) {
          setIsAOpen(false);
        } else if (scrolled < 0) {
          setIsAOpen(true);
        }
      });
    };
  }, [isAOpen]);

  return (
    <main>
      {isAOpen ? <ComponentA /> : <ComponentB />}
      <OtherComponent />
    </main>
  );
}

ComponentA.js

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

const ComponentA = () => {
  return (
    <main className="pA">
      <h1>COMPONENT-AYE</h1>
    </main>
  );
};

export default ComponentA;

ComponentB.js

import React, { useEffect } from "react";

const ComponentB = () => {
  useEffect(() => {
    console.log("ponent-B showing up");
  });
  return (
    <main className="pB">
      <h1>COMPONENT-Bee</h1>
    </main>
  );
};

export default ComponentB;

OtherComponent.js

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

const OtherComponent = () => {
  return (
    <main className="pOther">
      <h1>OTHER COMPONENT AND DATA</h1>
    </main>
  );
};

export default OtherComponent;

For simplicity I have kept all the styles in styles.css file

style.css

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.App {
  font-family: sans-serif;
  text-align: center;
}

.pA,
.pB {
  height: 500px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pA {
  background: green;
}
.pB {
  background: rgb(238, 94, 58);
  margin-top: 500px;
}

.pOther {
  height: 130vh;
  background: rgb(58, 241, 241);
}

Note: you need to make some basic changes while scrolling back to top (perhaps remove the margin-top on ComponentB. That's an exercise for you. Cheers !!!)

You could use IntersectionObserver API:

https://developer.mozilla/en-US/docs/Web/API/Intersection_Observer_API

Here’s an example of it being used with React:

https://dev.to/producthackers/intersection-observer-using-react-49ko

You can use a library for handling scrolling enter or leave events. https://github./civiccc/react-waypoint

You can use onMouseLeave or onMoustOut event listener to check it , In react can be implemented like below

import "./styles.css";
import {useState} from 'react'

export default function App() {
  const [showA,setShowA]=useState(true)
  return (
    <div className="App">
      {showA ?  <div style={{width:'100%',height:'100vh',backgroundColor:"red"}} onMouseLeave={()=>setShowA(!showA)}></div>:     <div style={{width:'100%',height:'100vh',backgroundColor:"blue"}} onMouseLeave={()=>setShowA(!showA)}></div>}
    </div>
  );
}

You can refer to codesanbox below

I have a ponent A that renders once the application loads.

I am looking to render another ponent B the moment ponent A leaves
the screen. This happens when the user scrolls ponent A off screen.

And also when user scrolls ponent A back into the screen, ponent B should
disappear.

Looking for guidance on how I could track whether ponent A is on the screen or off screen in React.
Please advice.

Idea is below. Looking for a way to listen if ponent A is on screen or not and setShowB(false) or setShowB(true) accordingly.

import React, { useState } from 'react';

const AComponent = () => {
  const [showB, setShowB] = useState(false); // I do want this to be a boolean
  const setVisibility = (showB) => showB ? 'visible' : 'hidden'

  return (
    <div>

      <div id='A' style={{ visibility: setVisibility(showB)}}>
        I am ponent A
      </div>

      <div id='B'>
        I am ponent B
      </div>

    </div>
  );
};

export default AComponent;

Note: Not looking to use any external libraries.

On page load only Component A shows.

===================================================================

when ponent A is scrolled off screen ponent B shows up.

I have a ponent A that renders once the application loads.

I am looking to render another ponent B the moment ponent A leaves
the screen. This happens when the user scrolls ponent A off screen.

And also when user scrolls ponent A back into the screen, ponent B should
disappear.

Looking for guidance on how I could track whether ponent A is on the screen or off screen in React.
Please advice.

Idea is below. Looking for a way to listen if ponent A is on screen or not and setShowB(false) or setShowB(true) accordingly.

import React, { useState } from 'react';

const AComponent = () => {
  const [showB, setShowB] = useState(false); // I do want this to be a boolean
  const setVisibility = (showB) => showB ? 'visible' : 'hidden'

  return (
    <div>

      <div id='A' style={{ visibility: setVisibility(showB)}}>
        I am ponent A
      </div>

      <div id='B'>
        I am ponent B
      </div>

    </div>
  );
};

export default AComponent;

Note: Not looking to use any external libraries.

On page load only Component A shows.

===================================================================

when ponent A is scrolled off screen ponent B shows up.

Share Improve this question edited Jul 19, 2021 at 18:22 Fllappy asked Jul 19, 2021 at 17:39 FllappyFllappy 4015 silver badges14 bronze badges 15
  • Hello Mate ! I am trying to look for a React solution for you. As per the requirement, You are saying only 1 Component should be displayed at a time. When a user scrolls a particular Component , that particular ponent should be removed of the DOM and another should be shown up at its place. My question to scroll up to the height of the Component, we must have more content on the page so that we are able to scroll on the page. Could you share the design of what you want to achieve, so that I can try to e up with a solution. :) Thanks – Imran Rafiq Rather Commented Jul 19, 2021 at 18:13
  • I would like to connect with you friend for this particular scenario, because I am trying to create the exact scenario. If you wish we can do this together here. I do not have all the context :) – Imran Rafiq Rather Commented Jul 19, 2021 at 18:15
  • The scenario is going to be somewhat like this: codesandbox.io/s/help-friend-stackoverflow-x15jf – Imran Rafiq Rather Commented Jul 19, 2021 at 18:17
  • @Flappy: When you say "when ComponentA is scrolled off the screen", We can only scroll a Component when its height is greater than the ViewPort or we have more content below it. So that we can scroll. So, could you provide any design about what you wish to achieve. Is there more stuff below the ComponentA as it first loads. – Imran Rafiq Rather Commented Jul 19, 2021 at 18:23
  • @ImranRafiqRather Updated question if it it helps clarify. Component B is a Sticky Component always stays on the bottom. – Fllappy Commented Jul 19, 2021 at 18:23
 |  Show 10 more ments

4 Answers 4

Reset to default 1

You can try this solution and build on top of this as per your requirement. You need to use useEffect() Hook to put all your scrolling code and manage state accordingly. useEffect() is used to manage all the sideEffects and for user scrolling useEffect() is the best place to write our Logic.

CODESANDBOX: https://codesandbox.io/s/help-friend-stackoverflow-x15jf?file=/src/App.js

TOTAL COMPONENTS USED:

App.js

import "./styles.css";
import ComponentA from "./ponents/ComponentA";
import ComponentB from "./ponents/ComponentB";
import OtherComponent from "./ponents/OtherComponent";
import { useState, useEffect } from "react";

export default function App() {
  const [isAOpen, setIsAOpen] = useState(true);

  useEffect(() => {
    window.addEventListener("scroll", () => {
      // let ponentHeight = document.querySelector(".pA").clientHeight;
      let scrolled = window.scrollY;

      console.log(scrolled);

      if (scrolled >= 530) {
        setIsAOpen(false);
      } else if (scrolled <= 10) {
        setIsAOpen(true);
      }
    });

    return () => {
      window.removeEventListener("scroll", () => {
        // let ponentHeight = document.querySelector(".pA").clientHeight;
        let scrolled = window.scrollY;

        console.log(scrolled);

        if (scrolled >= 530) {
          setIsAOpen(false);
        } else if (scrolled < 0) {
          setIsAOpen(true);
        }
      });
    };
  }, [isAOpen]);

  return (
    <main>
      {isAOpen ? <ComponentA /> : <ComponentB />}
      <OtherComponent />
    </main>
  );
}

ComponentA.js

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

const ComponentA = () => {
  return (
    <main className="pA">
      <h1>COMPONENT-AYE</h1>
    </main>
  );
};

export default ComponentA;

ComponentB.js

import React, { useEffect } from "react";

const ComponentB = () => {
  useEffect(() => {
    console.log("ponent-B showing up");
  });
  return (
    <main className="pB">
      <h1>COMPONENT-Bee</h1>
    </main>
  );
};

export default ComponentB;

OtherComponent.js

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

const OtherComponent = () => {
  return (
    <main className="pOther">
      <h1>OTHER COMPONENT AND DATA</h1>
    </main>
  );
};

export default OtherComponent;

For simplicity I have kept all the styles in styles.css file

style.css

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.App {
  font-family: sans-serif;
  text-align: center;
}

.pA,
.pB {
  height: 500px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pA {
  background: green;
}
.pB {
  background: rgb(238, 94, 58);
  margin-top: 500px;
}

.pOther {
  height: 130vh;
  background: rgb(58, 241, 241);
}

Note: you need to make some basic changes while scrolling back to top (perhaps remove the margin-top on ComponentB. That's an exercise for you. Cheers !!!)

You could use IntersectionObserver API:

https://developer.mozilla/en-US/docs/Web/API/Intersection_Observer_API

Here’s an example of it being used with React:

https://dev.to/producthackers/intersection-observer-using-react-49ko

You can use a library for handling scrolling enter or leave events. https://github./civiccc/react-waypoint

You can use onMouseLeave or onMoustOut event listener to check it , In react can be implemented like below

import "./styles.css";
import {useState} from 'react'

export default function App() {
  const [showA,setShowA]=useState(true)
  return (
    <div className="App">
      {showA ?  <div style={{width:'100%',height:'100vh',backgroundColor:"red"}} onMouseLeave={()=>setShowA(!showA)}></div>:     <div style={{width:'100%',height:'100vh',backgroundColor:"blue"}} onMouseLeave={()=>setShowA(!showA)}></div>}
    </div>
  );
}

You can refer to codesanbox below

本文标签: javascriptTrack if a component is on or off screenStack Overflow