jwt-react-tools
v2.0.5
Published
React HOC to make usage of JWT extremely fun
Downloads
2
Readme
JWT React Tools
React HOC to make usage of JWT extremely fun
Installation
yarn add jwt-xhr-hook
or npm i --save jwt-xhr-hook
if you are still using npm
Usage
This package provides a decorator to add isAuthenticated flag and jwtPayload inside component's props and child context
import React, { Component, PropTypes } from 'react';
import JWT from 'jwt-react-tools';
@JWT()
class Main extends Component {
render() {
return (
<div>foo</div>
);
}
}
This will provide isAuthenticated flag and jwtPayload object from token stored in Local Storage by key 'jwt'. If you want to load JWT from another key pass key name through argument.
import React, { Component, PropTypes } from 'react';
import JWT from 'jwt-react-tools';
@JWT('customKey')
class Main extends Component {
render() {
return (
<div>foo</div>
);
}
}
Access data inside child context
import React, { PropTypes } from 'react';
const Menu = (props, { isAuthenticated, jwtPayload }) => (
<nav className={ s.header }>
<ul>
<li>
<IndexLink to="/" activeClassName={ s.active }>JWT</IndexLink>
</li>
{isAuthenticated &&
<li>
<Link to="/" activeClassName={ s.active }>{jwtPayload.sub}</Link>
</li>
}
{isAuthenticated &&
<li>
<Link to="/users" activeClassName={ s.active }>Users</Link>
</li>
}
<li>
<Link to="/github" activeClassName={ s.active }>GitHub</Link>
</li>
{!isAuthenticated &&
<li>
<Link to="/sign-in" activeClassName={ s.active }>Sign In</Link>
</li>
}
{!isAuthenticated &&
<li>
<Link to="/sign-up" activeClassName={ s.active }>Sign Up</Link>
</li>
}
{isAuthenticated &&
<li className={ s.pullRight }>
<button onClick={ onLogout }>Logout</button>
</li>
}
</ul>
</nav>
);
Menu.contextTypes = {
isAuthenticated: PropTypes.bool,
jwtPayload: PropTypes.object,
};
Contributing
PR's are welcome 👍
Credits
Maintained by Albert Fazullin, hex22a
Twitter: @hex22a