Coder Social home page Coder Social logo

oklas / react-breadcrumbs-dynamic Goto Github PK

View Code? Open in Web Editor NEW
125.0 8.0 30.0 2.48 MB

:house_with_garden: > breadcrumbs > extremely flexible > and > easy to use

License: MIT License

JavaScript 96.77% HTML 3.23%
breadcrumbs theme react breadcrumbs-item breadcrumb breadcrumb-navigation breadcrumbs-flexible breadcrumbs-dynamic

react-breadcrumbs-dynamic's Introduction

react-breadcrumbs-dynamic

Npm package Npm downloads Travis build status Test Coverage Dependency Status Dependency Status Dependency Status


๐Ÿ  > React dynamic breadcrumbs > extremely flexible > and > easy to use

This is completely router-independent solution. You can use it with any version of React Router (2 or 3 or 4) or any other routing library for React or without routing at all. All what you need is just to specify components for breadcrumbs items and its props. However props and components should be specified separately. Props should be specified in intermediator component BreadcrumbsItem anywhere in your hierarchy of components and routes.

Visit live DEMO (source code of demo in example folder)

Synopsis

const Profile = ({user}) => (
  <div>

    <BreadcrumbsItem
      to=`/user/${user.login}`
      icon='account-box'
    >
      {user.firstName} {user.lastName}
    </BreadcrumbsItem>

    <h1>
      {user.firstName} {user.lastName}
    </h1>
  </div>
)

Installation

npm install --save react-through react-breadcrumbs-dynamic

# definitions may be installed if typescript is used
# ( worked for 1.0.10, leave feedback if any )
npm install --save @types/react-breadcrumbs-dynamic

Base configuration

Do you already use declarative communications through react tree with react-through? Just add <ThroughProvider/> to the root of your React component tree:

import {ThroughProvider} from 'react-through'

const theApp = (
  <ThroughProvider>
    <App />
  </ThroughProvider>
)

ReactDOM.render(theApp, document.getElementById('root'))

Instance configuration

In this example the react-router v4 <NavLink> is used as breadcrumbs item:

import {Breadcrumbs} from 'react-breadcrumbs-dynamic'

const Page = (props) => (
  return (
    <div className="App">
      <Header>

        <Breadcrumbs
          separator={<b> / </b>}
          item={NavLink}
          finalItem={'b'}
          finalProps={{
            style: {color: 'red'}
          }}
        />

      </Header>

      {props.children}

      <Footer>
        <Breadcrumbs/>
      </Footer>
    </div>
  )
}

Please note that item and finalItem require react component (class) instead of react element. However separator requires react element.

By default order of items is based on URL length. You can override the sort order as you like just specify comparision function in compare prop which receive pair of objects containing props of breadcrumbs item. For example: <Breadcrumbs compare={(a,b)=>a.weight-b.weight} removeProps={{weight: true}} />.

If you use <a> tag based items then you will find renameProps or duplicateProps useful to map prop to on prop href like this: <Breadcrumbs renameProps={{to:"href"}} />.

Adding items to breadcrumbs

Each routed component in your react tree is generally associated with route and with correspondent breadcrumbs. Each component may add its breadcrumbs item by rendering <BreadcrumbsItem> with any props and children.

Example tree of routed components with breadcrumbs items:

import {BreadcrumbsItem} from 'react-breadcrumbs-dynamic'

const App = (props) => (
  <div>
    <BreadcrumbsItem to='/'>Main Page</BreadcrumbsItem>
    {props.children}
    <Route exact path="/user" component={User} />
  </div>
)

const User = (props) => (
  <div>
    <BreadcrumbsItem to='/user'>Home</BreadcrumbsItem>
    <h2>Home</h2>
    {props.children}
    <Route exact path="/user/contacts" component={Contacts} />
  </div>
)

const Contacts = (props) => (
  <div>
    <BreadcrumbsItem to='/user/contacts'>Contacts</BreadcrumbsItem>
    <h2>Contacts</h2>
    ...
  </div>
)

You can declaratively pass props with any data, functions, components and so on through react tree in any direction because react-through allows to do that.

Result

The result of above code will represent breadcrumbs like this:

  <NavLink to='/'>Main Page</NavLink>
  <b> / </b>
  <NavLink to='/user'>Home</NavLink>
  <b> / </b>
  <b to='/user/contacts'>Contacts</b>

If you use library or if you think that it is good for use - let people know about that - click the star.


The components and functions

Breadcrumbs component props

The breadcrumbs instance is implemented in the Breadcrumbs component, which is the through container in terms of react-through.

property type default description
separator element undefined separator between breadcrumbs items
item component a component of breadcrumbs items
finalItem component value of item prop component of final breadcrumbs item
finalProps object {} final item props - will override specified in BreadcrumbsItem
container component span wrapper component
containerProps object {} props for container component
compare function (a,b)=>a.to.length-b.to.length comparision function for sorting items
hideIfEmpty boolean false show or hide breadcrumbs container if items exist or not
renameProps object {} rename props passed from item BreadcrumbsItem to item
duplicateProps object {} duplicate props passed from item BreadcrumbsItem to item
removeProps object {} props aren't passed from item BreadcrumbsItem to item

BreadcrumbsItem component props

The BreadcrumbsItem component is the through agent with bearing key in prop to in terms of react-through.

The BreadcrumbsItem component may have any prop and may have children. Each prop for BreadcrumbsItem will be passed to correspondent breadcrumb component specified in item or finalItem prop of Breadcrumbs. Only one prop is mandatory.

property type default description
to string required mandatory required bearing key with URL
... any any properties - will be mapped to correspondent breadcrumb item

withBreadcrumbsItem() function

Advanced usage higher order component function. It acquire one argument with your custom react component and return appropriate component which will have breadcrumbs in its props with methods item() and items() like throughAgent from react-through.

this.props.breadcrumbs.item() and this.props.breadcrumbs.items()

Advanced usage methods to configure breadcrumbs item of your react component. These methods will be added to props by HOC of withBreadcrumbsItem function. The function item() accepts one react component with props and the functions items() accepts react component with children which may contain any number of components to create correspondent number of breadcrumbs item. The breadcrumbs item for these functions may be any react component and only props is significant. The Dummy and the Item components is exported by library for this case. Each function accepts null to reset breadcrumbs items to none if current component is no more needed to represent any breadcrumbs items.

constants

The through area name used by this library is defined in breadcrumbsThroughArea variable.

The prop name which contain bearing key is defined in breadcrumbsBearingKey.

import { breadcrumbsThroughArea } from 'react-breadcrumbs-dynamic'
import { breadcrumbsBearingKey } from 'react-breadcrumbs-dynamic'

LICENSE

react-breadcrumbs-dynamic's People

Contributors

amazingturtle avatar ok2ju avatar oklas avatar wadamssoyfiesta avatar zmeecer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-breadcrumbs-dynamic's Issues

Use case without react router

Is their any examples that use this package but doesn't use react router. for example I want to make an app that uses react router but I don't want the url to change with the breadcrumbs. I want the path to show in the breadcrumbs not url.

Semantic Versioning

That's an awesome package, really
But, could you use semantic versioning cuz your last versions have broken my builds
Thanks!

BreadcrumbsItem cannot work with Jest

When using JEST, a exception will be thrown if is used.

class xx {
render (){
return (
<BreadcrumbsItem key="1" to="/test/tt">
test
</BreadcrumbsItem>
);
}
}

TypeError: Cannot read property 'add' of undefined
at node_modules/react-through/lib/throughAgent.js:103:42
at Array.forEach ()
at ThroughAgent._this.update (node_modules/react-through/lib/throughAgent.js:101:15)
at Object.ThroughAgent._this.item (node_modules/react-through/lib/throughAgent.js:74:17)
at ThroughAgent._this.configureItem.notused [as configureItem] (node_modules/react-through/lib/throughAgentFactory
.js:75:21)
at ThroughAgent.componentWillMount (node_modules/react-through/lib/throughAgentFactory.js:87:14)
at callComponentWillMount (node_modules/react-dom/cjs/react-dom.development.js:11507:14)
at mountClassInstance (node_modules/react-dom/cjs/react-dom.development.js:11590:5)
at updateClassComponent (node_modules/react-dom/cjs/react-dom.development.js:13145:7)
at beginWork (node_modules/react-dom/cjs/react-dom.development.js:13824:14)
at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:15863:12)
at workLoop (node_modules/react-dom/cjs/react-dom.development.js:15902:24)
at renderRoot (node_modules/react-dom/cjs/react-dom.development.js:15942:7)
at performWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:16560:22)
at performWork (node_modules/react-dom/cjs/react-dom.development.js:16482:7)
at performSyncWork (node_modules/react-dom/cjs/react-dom.development.js:16454:3)
at requestWork (node_modules/react-dom/cjs/react-dom.development.js:16354:5)
at scheduleWork$1 (node_modules/react-dom/cjs/react-dom.development.js:16218:11)
at scheduleRootUpdate (node_modules/react-dom/cjs/react-dom.development.js:16785:3)
at updateContainerAtExpirationTime (node_modules/react-dom/cjs/react-dom.development.js:16812:10)
at updateContainer (node_modules/react-dom/cjs/react-dom.development.js:16839:10)
at ReactRoot.Object..ReactRoot.render (node_modules/react-dom/cjs/react-dom.development.js:17122:3)
at node_modules/react-dom/cjs/react-dom.development.js:17262:14
at unbatchedUpdates (node_modules/react-dom/cjs/react-dom.development.js:16679:10)
at legacyRenderSubtreeIntoContainer (node_modules/react-dom/cjs/react-dom.development.js:17258:5)
at Object.render (node_modules/react-dom/cjs/react-dom.development.js:17317:12)
at Object.render (node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:218:50)
at new ReactWrapper (node_modules/enzyme/build/ReactWrapper.js:130:16)
at Object.mount (node_modules/enzyme/build/mount.js:21:10)
at mountDocumentation (tests/xxx/Documentation/Documentation.test.tsx:28:23)
at Object.beforeEach (tests/xxx/Documentation/Documentation.test.tsx:35:32)

I can't get it to work

Hi, I don't know what I'm doing wrong. I run the example locally and it works perfectly, but when i try to implement it in my project does not work :(, I am using all the default props. Any help?

It should be rendering Home / Table / Create but is rendering only the last item
image

  • App.js

image

  • Body.js

image

  • ABMMain.js

image

  • ABMCrear.js

image

Props type mismatch

The lib offers a compare prop but it is not defined in types. Due to this it throws a type error while using in typescript.
image
image

Legacy context API has been detected within a strict-mode tree.

I have
"react-breadcrumbs-dynamic": "^1.2.1",
"react-through": "^1.1.4",

And have the Warning in console

Legacy context API has been detected within a strict-mode tree.

The old API will be supported in all 16.x releases, but applications using it should migrate to the new version.

Please update the following components: ThroughAgent

Learn more about this warning here: https://fb.me/react-legacy-context
    in ThroughAgent

It Doesnt work with react loadable

Im using react loadable in my project , after installed react-breadcrumbs-dynamic and configured it like documents breadcrub just show the current item neither the others

firefox browser getting order error not in ChromeBrowser

I am adding one attribute(name as:depth) to BreadcrumbsItem and changing order of BreadcrumbsItems. its perfectly working in chrome after reloading successfully. But while testing in firefox it giving rendomly displaying.

BreadcrumbsItem to="/" depth="1" depth="2" depth="3"

to render in order i wrote code in Breadcrumbs
<Breadcrumbs
separator={ / }
item={Link}
finalItem={'b'}
compare={function(a,b){
if(parseInt(a.depth)< parseInt(b.depth)){
return -1;
}
return 0;
}}
/>

New props not reflected in render

Hi,

Prop changes for children aren't being displayed properly. I think there's a problem in componentWillReceiveProps.

Awesome component btw!

Pass props to Item

Hi,

First of all really nice what you've done.
i have a suggestion for a feature / improvement.
We could add ...props to item to allow us to pass custom props (style more precisely for my case !!) to it.

use cases
I have a NavLink if i want to style it to not have any decoration in the text i have to do :

const Nav = props => (
  <NavLink
    {...props}
    style={{ textDecoration: 'none' }} >
    {props.children}
  </NavLink>
);

<Breadcrumbs separator={<strong> / </strong>} item={Nav} finalItem="strong" />

How to solve it
Add for example itemProps to Breadcrumbs

const itemProps = props.itemProps 

    <Container {...containerProps}>
      {itemsValue.map((itemValue, i) => {
        return i+1 < count ? (
          separator ? (
            <span key={i}>
              <Item {...prepareProps(itemValue, rename, duplicate, remove)} {...itemProps} />
              {separator}
            </span>
          ) : (
            <Item key={i} {...prepareProps(itemValue, rename, duplicate, remove)} {...itemProps} />
          )
        ) : (
          <FinalItem key={i}
            {...prepareProps(itemValue, rename, duplicate, remove)}
            {...finalProps}
          />
        )
      })}
    </Container>

TypeError: Cannot read property 'subscribe' of undefined

I instantiated the <Breadcrumbs /> without any props, on one of my pages in a react-router-dom v4 app.

Through.updateArea
C:/code/ta/react-admin-frontend/node_modules/react-through/lib/Through.js:147
  144 |   key: 'updateArea',
  145 |   value: function updateArea(area) {
  146 |     if (this.unsubscribe) this.unsubscribe();
> 147 |     if (area) this.unsubscribe = this.context.through.subscribe(area, this.doUpdate);
      | ^  148 |   }
  149 | }, {
  150 |   key: 'render',

Issue with breadcrumb clickability

Hello and thanks for the great library, looks good so far.

I have a bit of an issue trying to make breadcrumbs clickable. I am using reactstrap as the display component for breadcrumbs. So I have a breadcrumbs component:

  <Breadcrumbs
     item={BreadcrumbItem}
     container={Breadcrumb}
     finalProps={{ active: true }}
  />

Breadcrumb and BreadcrumbItem are component from reacstrap.

And on the pages, I render for example

   <BreadcrumbsItem
          to={`/someroute`}>
          Equipment
   </BreadcrumbsItem>

This renders fine, but clicking the breadcrumbs does nothing, which I assume is because they are not rendered as links then.

I'm sure I am just misunderstanding something and this is not a huge issue, but if you could help clear this issue out it would be great.

Thanks in advance.

EDIT:

So I got some progress done by making a wrapper component like this:

const WrapperBread = ({ ...props }) => {
  return (
    <BreadcrumbItem {...props} tag={NavLink} />
  );
}

Now the only issue seems to be that all of the breadcrumbs are marked as "active" all the time, which worked before I started using this wrapper component.

Advanced usage with custom items

Hi

I have the Project page with route/project/:projectId and Task page with route /task/:taskId. Project page contains the list of tasks and clicking on it redirects the user to the Task page.
Those two pages have independent routes, defined on the top level. When displaying Task page I want to have a breadcrumb project_name -> task_name which requires some custom logic because the library will not display the whole chain since Task route is not nested inside the Project route.

How I can achieve that?

Cannot read property 'add' when doing renderToString

If I try to do ReactDOMServer.renderToString, my app breaks because of this line:

<BreadcrumbsItem to='/'>Home</BreadcrumbsItem>

The error is:

Unhandled Rejection (TypeError): Cannot read property 'add' of undefined

Add TypeDefinition(TypeScript support)

FYI @oklas

I wrote the TypeDefinition for your project.
and now we can use that as npm module.

npm install @types/react-breadcrumbs-dynamic

let me know if it has any problem. ๐Ÿ‘

please close it after reading.

breadcrumb data

Good evening, I have an issue with accessing breadcrumb data in my routes. Is it possible to go one step back according to its data and how can we get the data ? Thank you.

const myComponent = (props) => {
     const breadcrumbProps = props.something*
     const prevPath = breadcrumbProps.map(...)* || breadcrumbProps.prevPath*

     return (
          <Fragment>
                  <BreadcrumbsItem to={ somePathname }>Current Breadcrumb</BreadcrumbsItem>

                  <button onClick={() => goToPrevPath(prevPath)}>
                       Back
                  </button>
          </Fragment>
    )
}

Breadcrumbs appear in the wrong order for only ONE page

Hi, first of all thank you for your hard work with implementing this module.

I have this weird issue where on ONE page the breadcrumb order is messed up, while the rest of the pages are perfectly fine.

Here's some code that might help identify the issue.
The breadcrumbs are declared in the parent component along with 2 base items:

          <BreadcrumbsItem to="/">Home</BreadcrumbsItem>
          <BreadcrumbsItem to="/dashboard">
            <i className="material-icons">chevron_right</i>User
          </BreadcrumbsItem>
          <Breadcrumb />
          <div className="main">
            <Switch>
              <Route path="/dashboard" component={Dashboard} />
              <Route path="/risk-assessment" component={RiskAssessment} />
              <Route path="/bank-accounts" component={BankAccount} />
              <Route path="/scoring-decision" component={ScoringDecision} />
              <Route path="/financial-light" component={FinancialLight} />
              <Route path="/cle" component={CreditLineEstimations} />
            </Switch>
          </div>

All the pages have the BreadcrumbsItem on top of the page as in the examples and they work fine except the CreditLineEstimations page which shows them as:
Home > Credit line estimations > User
instead of
Home > User > Credit line estimations

the page render jsx starts as:

<div>
        <BreadcrumbsItem to="/cle">
          <i className="material-icons">chevron_right</i>Credit line estimations
        </BreadcrumbsItem>
...

PS: don't mind the separator added in the BreadcrumbsItem, it's wrong and it'll be fixed

Warning componentWillMount has been renamed

using V1.2.0 I have this warning with React V16.9.0.

Is it possible guys to fix that ?

Warning: componentWillMount has been renamed, and is not recommended for use. See https://fb.me/react-async-component-lifecycle-hooks for details.

  • Move code with side effects to componentDidMount, and set initial state in the constructor.
  • Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run npx react-codemod rename-unsafe-lifecycles in your project source folder.

Please update the following components: ThroughAgent, ThroughAgent.breadcrumbs

React 16 support?

Noticed that this library throws a warning for unmet peer dep when used with React 16.

Compound final item

Hello,

Is it possible to have a compound item, as final item?

Example:

finalItem={'span > strong'}

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.