some-react-components / react-scrollchor

A React component for scroll to `#hash` links with smooth animations
ISC License
149 stars 24 forks source link

NavItem with Scrollchor error - `<a>` cannot appear as a descendant of `<a>` #17

Closed sergical closed 7 years ago

sergical commented 7 years ago

From the following setup

import React from 'react';
import { Nav, NavItem } from 'react-bootstrap';
import Scrollchor from 'react-scrollchor';

const HomeNavigation = () => (
  <Nav pullRight>
    <NavItem><Scrollchor to="#how" className="nav-link">How?</Scrollchor></NavItem>
  </Nav>
);

export default HomeNavigation;

I get: Warning: validateDOMNesting(...): <a> cannot appear as a descendant of <a>. See HomeNavigation > NavItem > SafeAnchor > a > ... > Scrollchor > a

bySabi commented 7 years ago

@416serg thanks for report this. This is a common problem with NavItem.

Right now can be solve using a childrenless Scrollchor and simulateClick()

Example: Create this a file in: ./src/scrollchor-item.jsx

import React, { Component } from "react";
import Scrollchor from "react-scrollchor";

export default class ScrollchorItem extends Component {
  constructor(props) {
    super(props);
  }

  _handleClick = event => {
    this._back.simulateClick(event)
  };

  render() {
    const { to, children, className } = this.props;
    return <span onClick={this._handleClick} className={className} >
      <Scrollchor to={to} ref={ref => (this._back = ref)}/>
      {children}
    </span>
  }
}

and use it in your code:

import React from 'react';
import { Nav, NavItem } from 'react-bootstrap';
import ScrollchorItem from './src/scrollchor-item';

const HomeNavigation = () => (
  <Nav pullRight>
    <NavItem><ScrollchorItem to="#how" className="nav-link">How?</ScrollchorItem></NavItem>
  </Nav>
);

export default HomeNavigation;

Tell me how it was.

sergical commented 7 years ago

@bySabi 👍 🙏 thanks so much!