Achieve the hidden div scroll effect in React by initially hiding the div and then allowing

I am currently working on a web chat application using next.js. One of the features is an emoji picker button that, when clicked, displays a menu of emojis. The issue I am facing is that in order for the user to see the emoji menu, they have to scroll down. I attempted to use scrollIntoView() but it does not seem to be functioning correctly; I may be missing something.

import {Picker} from "emoji-mart";
const pickerRef = useRef()
const[showEmojis,setShowEmojis]=useState(false);

useEffect(() => {
  if(showEmojis) {
   pickerRef.current.scrollIntoView(true)
  }
} , [showEmojis])


return(
   <EmoticonContainer >
            
        {showEmojis && (<Picker ref={pickerRef} id="picker" style={{width: '100%'}} onSelect={addEmoji}/>)}
            
    </EmoticonContainer>
)

const EmoticonContainer=styled.div`
display:flex;
flex-direction:column;
`;

I attempted to implement this code but encountered an error message stating: TypeError: pickerRef.current.scrollIntoView is not a function

Answer №1

Why not try inserting a new div below the picker and then scroll to that div? This can be useful because sometimes those third-party libraries come with their own CSS styles that are difficult to override.

import {Picker} from "emoji-mart";
const pickerRef = useRef()
const[showEmojis,setShowEmojis]=useState(false);

useEffect(() => {
 
   pickerRef.current.scrollIntoView(true)
  
} , [showEmojis])


return(
<>
   <EmoticonContainer >
        <Picker id="picker" style={{width: '100%'}} onSelect={addEmoji}/>
    </EmoticonContainer>
    <div ref={emojiRef}></div>
</>
)

const EmoticonContainer=styled.div`
display:flex;
flex-direction:column;
`;

Give this method a try and you will see that it scrolls just as needed.

Answer №2

The initial hidden state means that pickerRef.current will return undefined, leading to the error as undefined does not possess the method .scrollIntoView. One way to resolve this is by using the optional chaining operator ?.

pickerRef.current?.scrollIntoView()

For more information, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Utilizing the optional chaining operator (?.) allows for accessing deeply nested object properties without needing to verify each part of the chain individually.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a typescript error: Attempting to access [key] in an unsafe manner on an object of

I have recently developed a thorough equality checking function. However, I am encountering an issue with the highlighted lines in my code. Does anyone have any suggestions on how to rectify this problem (or perhaps explain what the error signifies)? Her ...

`Finding the nodejs API route for displaying images from a database`

How can I successfully display an image from the database without getting a string of question marks instead? Click here to see the issue >>> When attempting to directly call the API using the provided link, the following result is returned: {&qu ...

What is the method to retrieve a client's IP address within Next.js 13?

I am working on a next.js 13 application and I need to integrate an API endpoint /api/getIP. The file route.js can be found at /app/api/getIP/route.js. To see the Minimal Reproduceable Code, visit: https://github.com/Nusab19/nextjs-test/tree/main/app I ...

Transform a REACT js Component into an HTML document

I'm working with a static React component that displays information from a database. My goal is to implement a function that enables users to download the React component as an HTML file when they click on a button. In essence, I want to give users ...

Unable to display elements from an array in the dropdown menu generated by v-for

Having just started learning Vue.js, I am facing a challenge in rendering the following array: countries: ["US", "UK", "EU" ] I want to display this array in a select menu: <select> <option disabled value="">Your Country</option& ...

I'm encountering an issue where the variable "user" cannot be found. This problem is arising while working with Firebase Auth alongside the most recent SDK version of Expo (SDK 42)

import { StyleSheet, Text, View } from "react-native"; import { NavigationContainer } from "@react-navigation/native"; import { createNativeStackNavigator } from "@react-navigation/native-stack"; import LoginScreen from " ...

Move the image inside the box without directly following the mouse cursor, but at a slightly faster pace

I am facing an issue with a Vue component that allows me to zoom in on an image and move it around the container. The problem is, when the image is zoomed in, it moves faster than the mouse due to using the scale transform. Additionally, I noticed that cl ...

Navigating through a complex nested JSON structure using Node.js

I am currently working on a Node.js app and I am facing difficulties in looping through an irregular JSON to extract and print its data. The JSON structure is as follows: { "courses": [ { "java": [ { "attendees": 43 }, ...

Please select the links located beneath the see-through triangular or polygonal shapes

Review the code snippet provided at the following link: http://jsfiddle.net/q8Ycz <div style="background-color: red; width: 200px;" onclick="alert('behind')"> <div><a href="test">test test test test test test test test test ...

Utilize the scope for promise .then() functions when calling a service

I've just started using AngularJS and I have a question about handling promises in controllers. In my controller, I'm calling a service that communicates with a webservice and returns a promise. I want to apply the data from the promise's s ...

What could be causing the lack of value appearing after I clicked the button?

Setting the value for the array of images as an empty string does not return the expected result. When I move one of the 4 images and click the button, I anticipate a new array with the information of one of the four images including src, x, and y coordina ...

Prevent the loading of a <img> element and replace it with a new one using CSS

Is there a way to hide an <img> element without accessing the HTML directly, only by using CSS? The <img> element does not have any specific class. Here is the HTML markup: <img title="Manual" id="imgAjuda" src="images/ico_aj.png" width=" ...

Sentry is causing issues with the build of my Next.js application

After integrating Sentry into my Next.js project, I have encountered an error that is preventing the application from building. The same error also occurs at runtime, but what confuses me is why it's affecting the build process. Is there a way to conf ...

A universal TypeScript type for functions that return other functions, where the ReturnType is based on the returned function's ReturnType

Greetings to all TypeScript-3-Gurus out there! I am in need of assistance in defining a generic type GuruMagic<T> that functions as follows: T represents a function that returns another function, such as this example: fetchUser(id: Id) => (disp ...

Issues with WordPress's multiple menu functionality not functioning as expected

I've been working on setting up multiple menus in WordPress, and I've run into a little issue. I managed to create the menus, assign them to their respective locations, and save them successfully. However, when I try to call the footer menu, it e ...

Index.js is dynamically importing a .tsx file post-build, with a specific focus on Windows

While working on my project, I decided to customize a module by cloning it and making some changes. After installing the dependencies and building it, I encountered an error when trying to run it. The error message stated: Error: Unable to resolve module & ...

Is there a way to initiate a jquery function upon loading the page, while ensuring its continued user interaction?

On my webpage, there is a JavaScript function using jQuery that I want to automatically start when the page loads. At the same time, I want to ensure that users can still interact with this function. This particular function involves selecting a link tha ...

What is causing my grayscale function to only impact part of the canvas?

As a beginner programmer, I have been experimenting with creating a grayscale function in JavaScript for practice. This is the code I have come up with: <canvas width='400' height='400'></canvas> <script> var can ...

The Ajax validation form mistakenly redirects the echoes to a different page instead of the intended page for displaying the output

I am currently working on creating an ajax-form to validate the client-side server of my sign-up form. My goal is to have error messages displayed on the same page where they are triggered, without loading a separate page. Below is the code from my (sign ...

Uploading files in javascript and PHP

I am currently utilizing an audio recorder provided by this source , However, instead of storing the file locally, I am interested in uploading it back to the server. My attempt involved adjusting the Recorder.setupDownload function within the recording. ...