Next.js Discord

Discord Forum

Unhandled Runtime ErrorError: Cannot access Levels.ONE on the server. You cannot dot into a client

Answered
dperolio posted this in #help-forum
Open in Discord
Avatar
So, I have a simple Heading client component:

'use client';

import classNames from 'classnames';

/**
 *
 */
const Levels = {
  ONE: 1,
  TWO: 2,
  THREE: 3,
  FOUR: 4,
  FIVE: 5,
  SIX: 6
};

function Heading ({
  level,
  looks,
  className,
  children,
  ...other
}: HeadingProps) {
  const HeadingLevel = `h${level}`;

  return (
    <HeadingLevel {...other} className={classNames('heading', className, { [`h${looks}`]: looks })}>
      {children}
    </HeadingLevel>
  );
}

Heading.Levels = Levels;

export default Heading;


Then in a page I have:

<Heading level={Heading.Levels.ONE}>
  Some Header Here
</Heading>
and I am receiving this error:
Unhandled Runtime Error
Error: Cannot access Levels.ONE on the server. You cannot dot into a client module from a server component. You can only pass the imported name through.

What am I doing wrong?
Answered by josh
Move Levels into a seperate file
View full answer

11 Replies

Avatar
Is the page that contains the Heading a RSC?
Avatar
Yeah, just a normal page.tsx
Why can't we do that?
Avatar
if that's the case, the error shows the issue: You're trying to access Levels which is declared inside the client component, which cannot be accessed from the server as it's bundled seperately
Avatar
Move Levels into a seperate file
Answer
Avatar
Seems dumb. :/
The whole point is to keep the properties of the component coupled with the component.
Avatar
don't shoot the messenger
Avatar
😅

So I guess, just do
export const ComponentProperties = {
  Heading: {
    Levels: {
      ONE: 1,
      TWO: 2,
      THREE: 3,
      FOUR: 4,
      FIVE: 5,
      SIX: 6
    }
  }
} as const;
in my constants file and move all my component properties like that to there...?
<Heading level={ComponentProperties.Heading.Levels.ONE}>
Or do you have a better recommendation?
Avatar
i would probably just keep it in a types.ts file alongside the Heading.tsx
Avatar
Okay, thank you.