Using a JavaScript command, connect a function from one file to another file

I attempted to import a function because I want to click on <il> servies</il> and scroll to the services section on the home page. However, I simply want to click on the li element in the navbar and scroll to the service section on the home page. Both pages are different which is why my module is not working on NEXT.JS

**Images of code ** navbar code image services page code image

**Facing ERROR *

Import trace for requested module:
./components/Navbar.js
wait  - compiling...
error - ./components/Navbar.js
Error:
  x Expected ',', got ':'
    ,-[D:\Next.js projects\help-desk\components\Navbar.js:8:1]
  8 |   const ref  = useRef();
  9 |   const scrollToSection = (elementRef) =>{
 10 |     window.scrollTo(
 11 |       top:elementRef.current.offsetTop,
    :          ^
 12 |       behavior: 'smooth'
 13 |     )
 13 |   }
    `----

Caused by:
    Syntax Error

Import trace for requested module:
./components/Navbar.js

navbar.js Code:

import React from 'react'
import Image from 'next/image'
import Link from 'next/link'
import { useRef } from 'react'
import { AiOutlineSearch } from 'react-icons/ai';
AiOutlineSearch
const Navbar = () => {
  const ref  = useRef();
  const scrollToSection = (elementRef) =>{
    window.scrollTo(
      top:elementRef.current.offsetTop,
      behavior: 'smooth'
    )
  }
  return (
    <>
    <div className='flex flex-col md:flex-row md:justify-start justify-center items-center py-1 drop-shadow-xl bg-slate-100'>
    <div className='logo mx-9 cursor-pointer'>
      <Image width={70} height={70} src="/navhome.png" alt=" " />
    </div>
    <div className="nav">
        <ul className='flex items-center space-x-6 font-bold md:text-md'>
          <Link legacyBehavior href={"/"}><a><li>Home</li></a></Link>
          <Link legacyBehavior href={"/about"}><a><li>About</li></a></Link>
          {/* <Link legacyBehavior href={"/servies"}><a><li>Services</li></a></Link> */}
          <li onClick={()=> scrollToSection(ref) href="#section"}>Services</li>
          <Link legacyBehavior href={"/contact"}><a><li>Contact</li></a></Link> 
        </ul>
      </div>
      <div className="search absolute right-0 top-6 mx-5">
       <AiOutlineSearch className='text-xl  md:text-3xl'/>
      </div>
    </div> 
    </> 
  )
}

export default Navbar;
export { scrollToSection };

index.js file:

import Image from 'next/image'
import Head from 'next/head'
import Link from 'next/link'
import  {scrollToSection}  from '../components/Navbar.js'
import Servies from '../pages/servies'

export default function Home() {
  return (
    <div>
      <Head>
        <title>HelpDesk.com - we're here to serve you </title>
        <meta name="description" content="HelpDesk.com - we're here to serve you" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <div>
        <img src="/home.jpg" alt="" />
      </div>
      <section ref={ref} className='scrollService' id='sectionid' >
        <Servies />
        </section>
      <br />
    </div>
    )
}

Answer №1

If you want to achieve the desired outcome, consider using the id attribute of your section as the target for a link.

<section id="section"/>

In order to do this in Next.js:

<Link href="#section"/>

For React:

<Link to="#section"/>

And in plain HTML:

<a href="#section">Scroll to section</a> 

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

Retrieve the information of the currently logged-in user on Discord using next-auth

Can anyone help me with extracting the banner and ID of the currently logged in user? Feel free to reach out at next@12 [email protected] I have successfully logged the profile details at the backend, but I'm facing issues pulling this informatio ...

Trouble is arising in rendering events with years before 100 (specifically years 0000 - 0099) when using the ISO8601 format in fullCalendar

I've created a Calendar that showcases various events using fullcalendar. The events span from the years 0001 to 6000. Fullcalendar requires dates in ISO8601 format, and I am providing them as such. Events from the years 0100-6000 render perfectly w ...

Using PHP to globally access a JavaScript object named

I have a collection of CSS attributes stored in a MySQL database that are accessed using PHP. These attributes need to be accessible to JavaScript once the page has finished loading. To achieve this, I loop through each row and create a JavaScript object ...

How to retrieve a property with a colon in JavaScript object

After parsing XML into JSON with xml2js, I found elements with colons like this: obj = { "data:example":"smthing"}; Is there a way to directly access these elements in JSON? Any tips or tricks? Thank you! ...

Eliminate jQuery's delayed blinking effect with the use of an event

Utilizing the mouseenter and mouseleave events, I have implemented a functionality to add a button (not actually a button) to an <li>. However, there seems to be a problem with my code. The button appears and disappears on mouseleave and mouseenter, ...

Can a script be executed on a node.js module?

I have been developing a node package with an installation script that establishes a basic application structure. This script simply creates a few folders and generates an "admin" user if one does not already exist. Currently, the script performs multiple ...

Downloading files from a Blob in NodeJS: A step-by-step guide

How do I retrieve a file from a BLOB column using NodeJS? Currently, I am utilizing the oracledb library for database operations and my code snippet is as follows: async function getFile(req, res) { let filename = req.params.filename; let file = a ...

What is the method to modify the background color of el-pagination?

I am using el-pagination on a dark page and I want to make its background color transparent. When I do not use the 'background' prop, the background color of el-pagination is white. Here is how it looks: (sorry I can't add an image) htt ...

Tips on creating a script for detecting changes in the table element's rows and columns with the specified data values

I have a div-based drop-down with its value stored in TD[data-value]. I am looking to write a script that will trigger when the TD data-value changes. Here is the format of the TD: <td data-value="some-id"> <div class="dropdown">some elements& ...

The functions Show() and Hide() may not work in all scenarios within jQuery

I'm currently developing a website that allows users to participate in quizzes. Each quiz consists of 20 questions divided into three sections: 1 mark for 10 questions, 2 marks for 5 questions, and 4 marks for 5 questions. For each question, there are ...

How to toggle the selection of all checkboxes in an AngularJS ng-repeat object array

Check out this Fiddle Example In my table, each row contains a checkbox and there is also a checkbox to check all rows and send the ID of the selected/all rows as JSON object. I have an array of objects from the server-side response (with pagination enab ...

Angular HttpClient not recognizing hashtag

I'm trying to make a REST API call, but running into issues with the developerId parameter being sent incorrectly: let developerId = "123#212"; let url = \`\${Constants.BASE_URL}\${marketId}/developers/\${developerId}\`; retur ...

Updating a webpage by re-rendering it upon passing an id parameter through the url in React

As a beginner in React JS, I have encountered a problem. In my index page, I defined the routes and called for the component using the following code: <Route path="/assignments/organization/:id" component={Manifest} /> Within the "manifest ...

Utilizing VueJs (Quasar) to access vuex store within the router

Recently, I have been diving into learning Vuex and creating an authentication module. Following a tutorial, I reached a point where I needed to use the store in the router. However, after importing my store at the top of the router index.js file, I notice ...

Enhancing data management with Vuex and Firebase database integration

Within my app, I am utilizing Firebase alongside Vuex. One particular action in Vuex looks like this: async deleteTodo({ commit }, id) { await fbs.database().ref(`/todolist/${store.state.auth.userId}/${id}`) .remove() .then ...

What is the correct method to remove an item from local storage?

Using localStorage, I have stored multiple objects in an array. Is there a way to remove just one object from this array? If I use localstorage.removeItem(keysofthelocalstorage), I can delete the entire array, but I specifically want to remove only certai ...

Combining several meshes in ThreeJS while maintaining distinct materials

I seem to be facing a dilemma. I am attempting to consolidate several meshes into one in order to optimize draw calls. Each mesh I have comes with its own unique material, whether it be color or texture. Below is the snippet of code I have been working on ...

Difficulty in Rendering Data with Next Js

I'm currently working on integrating data from an API by following the steps outlined in the Next documentation. Unfortunately, I am experiencing difficulties as the data is not rendering. This project marks my first venture into React, so I may be ov ...

Refreshing data attribute following an ajax request

I have this page with a list of various job listings. Each job listing has a button labeled "Paid" that includes a data-paid attribute indicating whether the job is paid or not. Whenever the "Paid" button is clicked, it sends a request to my route which u ...

New to NodeJS: Utilizing Requestify to Retrieve Data from Another URL

As a newcomer in the world of NodeJs, I am faced with the task of transitioning my CodeIgniter server APIs to Node.js. Currently, I am utilizing requestify to retrieve data from a web service, and once this is accomplished, I intend to invoke an insert met ...