react-native-router-flux throws Actions is not defined - undefined

Trying to start with a super simple react-native-router-flux example using 4.0.0-beta.28. I receive the dreaded red screen that the Action is undefined. I am guessing I have something semantically incorrect?
Here's my code:
import React, {Component} from 'react'
import {Scene,Router} from 'react-native-router-flux';
import LoginScreen from '../shoppinglist/screens/login'
import LandingScreen from '../shoppinglist/screens/landing'
import {
Platform,
AppRegistry
} from 'react-native';
const MyApp = () => {
return (
<Router>
<Scene key={"root"}>
<Scene key="login" component={LoginScreen} title="Login">
</Scene>
<Scene key="home" component={LandingScreen} title="Home" initial></Scene>
</Scene>
</Router>
)
}
AppRegistry.registerComponent('shoppinglist', () => MyApp)
Code that triggers Action:
<Button onPress={() => Actions.home()} title={'Navigate to Login'} />
Simulator error

You're missing Actions from your import directive:
import { Actions, Scene, Router } from 'react-native-router-flux';

Related

Warning: [react-router] Location "/add" did not match any routes

I am stuck with react-router routing. I am getting the error:
Warning: [react-router] Location "/add" did not match any routes`
// conf.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link} from "react-router-dom";
import add from './add';
import { createBrowserHistory } from 'history';
import confv1 from './confv1';
var button =React.createElement(Link, {
to: "/add"
}, React.createElement("button", {
type: "button"
}, "Add a project"));
export default class Root extends Component {
render() {
return (
React.createElement(Router, {
history: createBrowserHistory()
}, React.createElement(Route, {
path: "/conf",
component: confv1
}, React.createElement(Route, {
component: conf
}), React.createElement(Route, {
path: "/add",
component: add
})
)));
// );this is the conf page
and this is the add page when I refresh it I got the error "Warning: [react-router] Location "/add" did not match any routes`"
}
}
`
I resolved the error with a routes.js
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './App';
import conf from './conf';
import add from './add';
export default (
<Route path="/" component={App}>
<IndexRoute component={conf} />
<Route path="/conf" component={conf} >
<IndexRoute component={add} />
<Route path="/add" component={add} />
</Route>
</Route>
);
//index.js
import 'babel-polyfill';
import React from 'react';
import {render} from 'react-dom';
import {Router, BrowserRouter } from 'react-router';
import routes from './routes';
import {browserHistory} from 'react-router';
const history = require("history").createBrowserHistory();
render(
<Router history={browserHistory} routes={routes} />, document.getElementById('root')
)
but when I refresh the add page nothing shows in the contententer image description here
I noticed from your code snippet that you are using two different npm packages, and I am wondering if that is part of the issue.
under Config.js you called:
import { BrowserRouter as Router, Route, Link} from "react-router-dom";
Then under index.js you called:
import {Router, BrowserRouter } from 'react-router';
if that doesn't fix the issue could you create a codesandbox so I can take a look?
https://codesandbox.io/
Here is more information about the two npm packages you were trying to use:
https://www.npmjs.com/package/react-router
https://www.npmjs.com/package/react-router-dom
good luck!

MemoryRouter and jest test

https://reacttraining.com/react-router/web/guides/testing
The react-router testing documentation is bit obscure to me.
How to write a test to check a route is rendered
A Component. - APage.js
import React, { Component } from 'react'
export default class APage extends Component {
render() {
return (
<div>
A Page
</div>
)
}
}
Writing a unit test to check , as per documentation.
routes.test.js
import React from 'react'
import { render } from "react-dom";
import APage from './APage'
import {MemoryRouter} from 'react-router-dom';
test("render route", () => {
render(
<MemoryRouter initialEntries={["/apage"]}>
<APage />
</MemoryRouter>
);
});
It gives an error,
Invariant Violation: Target container is not a DOM element.
for render.
How do I write a basic test, like to test a component is rendered on a route.
I'd like to comment on Remi's solution, since the API in React Router v6 is a little different (and the link to the docs leads now to a 404):
import { Router } from 'react-router-dom';
test("render route", () => {
const history = createMemoryHistory();
render(
<Router
location={history.location} // history.location has a default value of '/'
navigator={history}
>
<APage />
</Router>
);
})
see github repo here
I think you should use Router instead. Since that uses BrowserRouter. (see alternatives section on react router example page)
import { Router } from 'react-router-dom';
test("render route", () => {
const history = createMemoryHistory();
history.push('/apage');
render(
<Router history={history}>
<APage />
</Router>
);
});
It could be that you should also add your page in a Route, but I'm not sure.
Then it would be something like:
import { Router, Route } from 'react-router-dom';
test("render route", () => {
const history = createMemoryHistory();
history.push('/apage');
render(
<Router history={history}>
<Route path='/aroute' render={(props) => (<APage {...props} />)} />
</Router>
);
});
Ok. Route testing has to be done by enzyme. not just using jest.
Followed https://medium.com/#antonybudianto/react-router-testing-with-jest-and-enzyme-17294fefd303
Used enzyme mount to test.

appbar responsive with options with react router v4, material-ui and apollo client

I'm working with apollo client, react, reac routerv4 and material-ui, my app is working ,
before insert material-ui i had
<Link to="/" className="navbar">React + GraphQL Tutorial</Link>
then i've inserted material-ui
<AppBar
title="Title"
iconClassNameRight="muidocs-icon-navigation-expand-more"
/>
but it's not clear for me how to add links for the title and options, in responsive mode with small screen the options i think must be invisible, in small screen not.
The official material-ui site is not well explained by example like bootstrap, so i need a litlle of help.
the full code is:
import React, { Component } from 'react';
import {
BrowserRouter,
Link,
Route,
Switch,
} from 'react-router-dom';
import './App.css';
import ChannelsListWithData from './components/ChannelsListWithData';
import NotFound from './components/NotFound';
import ChannelDetails from './components/ChannelDetails';
import AppBar from 'material-ui/AppBar';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {
ApolloClient,
ApolloProvider,
createNetworkInterface,
toIdValue,
} from 'react-apollo';
const networkInterface = createNetworkInterface({ uri: 'http://localhost:4000/graphql' });
networkInterface.use([{
applyMiddleware(req, next) {
setTimeout(next, 500);
},
}]);
function dataIdFromObject (result) {
if (result.__typename) {
if (result.id !== undefined) {
return `${result.__typename}:${result.id}`;
}
}
return null;
}
// customResolvers:
// This custom resolver tells Apollo Client to check its cache for a Channel object with ID $channelId
// whenever we make a channel query. If it finds a channel with that ID in the cache,
// it will not make a request to the server.
const client = new ApolloClient({
networkInterface,
customResolvers: {
Query: {
channel: (_, args) => {
return toIdValue(dataIdFromObject({ __typename: 'Channel', id: args['id'] }))
},
},
},
dataIdFromObject,
});
class App extends Component {
render() {
return (
<ApolloProvider client={client}>
<BrowserRouter>
<MuiThemeProvider muiTheme={getMuiTheme()}>
<div className="App">
<Link to="/" className="navbar">React + GraphQL Tutorial</Link>
<AppBar
title="Title"
iconClassNameRight="muidocs-icon-navigation-expand-more"
/>
<Switch>
<Route exact path="/" component={ChannelsListWithData}/>
<Route path="/channel/:channelId" component={ChannelDetails}/>
<Route component={ NotFound }/>
</Switch>
</div>
</MuiThemeProvider>
</BrowserRouter>
</ApolloProvider>
);
}
}
export default App;
the right is add a code like this:
<AppBar position="static">
<Toolbar>
<IconButton color="contrast" aria-label="Menu">
</IconButton>
<Typography type="title" color="inherit" >
{"Admin"}
</Typography>
<AuthLink to="/customers" label="Customers"/>
<AuthLink to="/tours" label="Tours"/>
<AuthLink to="/signout" label="Sign Out"/>
<AuthLink to="/signin" label=" Sign In" whenLogged="false"/>
</Toolbar>
</AppBar>
Authlink is just a component that I wrote to show the options and where simple I add the Title to display options.
const AuthLink = (props) => {
let auth = checkAuth();
return (
( (auth && !props.whenLogged ) || (!auth && props.whenLogged == "false") ) ? (
<Link to={props.to} className="navbar"><Button>{props.label}</Button></Link>
) : (
null
)
);
}
"Button" is a component from material, "Link" from react-router, here the imports:
import {
BrowserRouter,
Link,
Route,
Switch,
Redirect,
} from 'react-router-dom';
import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import Typography from 'material-ui/Typography';
import Button from 'material-ui/Button';
import IconButton from 'material-ui/IconButton';

Testing method in react component don't work

I have simple component in React. I want to test method in this component when user click button. I have test for that but finally don't pass.
Component:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import axios from 'axios';
class TestInvokingMethod extends Component {
onClick() {
}
render() {
return (
<div>
<input id='buttonTest' type='button' value={10} onClick={this.onClick} />
</div>
);
}
}
export default TestInvokingMethod;
And test for that:
import React from 'react';
import { shallow } from 'enzyme';
import TestInvokingMethod from '../../components/TestComponent/TestInvokeMethod';
const component = shallow(
<TestInvokingMethod />
);
test('Testing invoke method', () => {
const mockFn = jest.fn();
component.instance().onClick = mockFn;
component.update();
component.find('#buttonTest').simulate('click');
expect(component.instance().onClick.mock.calls.length).toBe(1);
});
Try using Jest's SpyOn
const spy = expect.spyOn(wrapper.instance(), "onClick");
wrapper.update();
wrapper.find('#buttonTest').simulate('click');
expect(spy).toHaveBeenCalled();
In addition to Garry's answer. In scenarios where wrapper.update() does not work, try updating its instance forcefully using wrapper.instance().forceUpdate().

RouteHandler: React.createElement: type should not be null, undefined, boolean, or number

The use of RouteHanlder gives two errors:
VM2805 bundle.js:9597Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).
Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
The structure of my application.
src
-- components
-- -- App.jsx
-- -- LengthModule.jsx
-- index.jsx
-- routes.js
My routes.js file
var React = require('react');
var Router = require('react-router');
var DefaultRoute = Router.DefaultRoute;
var Route = Router.Route;
var routes = (
<Route name="app" path="/" handler={require('./components/app.jsx')}>
<DefaultRoute handler={require('./components/LengthModule.jsx')} />
</Route>
)
index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.jsx';
ReactDOM.render(<div><App /></div>, document.getElementById('app'));
App.jsx
import React from 'react';
import { Router, RouteHandler } from 'react-router';
export class App extends React.Component {
render () {
return <div>
<RouteHandler />
</div>;
}
}
LengthModule.jsx
import React from 'react';
import Router from 'react-router';
export class LengthModule extends React.Component {
render () {
return <div>"Hello World"</div>;
}
}
Am I using RouteHandler correctly? What am I missing? Are there any alternatives?
App.jsx
import React from 'react';
import { Router, RouteHandler } from 'react-router';
export default class App extends React.Component {
render () {
return <div>
<RouteHandler />
</div>;
}
}
LengthModule.jsx
import React from 'react';
import Router from 'react-router';
export defaulf class LengthModule extends React.Component {
render () {
return <div>"Hello World"</div>;
}
}
Why es6 react component works only with "export default"?
Newer tutorials warn: Be Careful About Deprecated Syntax. This article specifically mentions "<RouteHandler /> is Deprecated."