Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can we have a level in the children? #54

Open
SvenDowideit opened this issue Feb 28, 2025 · 2 comments
Open

Can we have a level in the children? #54

SvenDowideit opened this issue Feb 28, 2025 · 2 comments

Comments

@SvenDowideit
Copy link

SvenDowideit commented Feb 28, 2025

I just wanted to do some conditional rendering of the child based on the heading level, and was surprised there wasn't some magic for me - so I used a State

I wonder if there's a better way, or if not, that it might be documented for future users :)

  const [levelNumber, setLevelNumber] = useState(1);

return (
      <Section
        component={
          <H
            render={({ level, Component }) => (
              setLevelNumber(level), (<Component className={`font-bold ${headingLevelClasses[level]} ${className}`}>{heading}</Component>)
            )}
          />
        }
      >
        {levelNumber == 1 && (
          <div>
            <HelpLink className="mr-2" helpUrl={helpUrl} />
          </div>
        )}
        <div className="col-span-2">{children}</div>
      </Section>
);

@alexnault
Copy link
Owner

alexnault commented Feb 28, 2025

Hi Sven, thanks for the question!

The current solution is to use the useLevel hook. Something along those lines:

function Parent() {
  return (
    <Section
      component={
        <H
          render={({ level, Component }) => (
            <Component
              className={`font-bold ${headingLevelClasses[level]} ${className}`}
            >
              {heading}
            </Component>
          )}
        />
      }
    >
      <Child />
      <div className="col-span-2">{children}</div>
    </Section>
  );
}

function Child() {
  const { level } = useLevel(); // level is 1 level deeper than parent now

  if (level !== 1) {
    return null;
  }

  return (
    <div>
      <HelpLink className="mr-2" helpUrl={helpUrl} />
    </div>
  );
}

Another solution would be for react-headings to support children as a render prop, but that would make it harder to read then it already is imo. Food for thought.

Cheers!

@SvenDowideit
Copy link
Author

mmm, so, your comment const { level } = useLevel(); // level is 1 level deeper than parent now is interesting - what i'm experiencing, is that it's a H1 header, but in the child, level == 2 - I'm assuming that your example should just change the if, reasonable, but it does lead to some harder to read code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants