react router not working for nested components(transitionTo is invalid) - javascript

I have parent grandchild dependency in my code.The main element is App.js
import React from 'react'
import ReactDOM from 'react-dom'
import {ExpenseApp} from './expense-app.js'
import {Switch, BrowserRouter, Route} from 'react-router-dom'
import {FullBlog} from './FullBlog.js'
class App extends React.Component{
render(){
return(
<BrowserRouter>
<Route path='/' component={ExpenseApp}/>
<Route path='/fullblog' component={FullBlog}/>
</BrowserRouter>
)
}
}
ReactDOM.render(<ExpenseApp data={data}/>, document.getElementById('container'))
The expenseapp.js has a button through which I want another page to get loaded
import React from 'react';
import ReactDom from 'react-dom' ;
import $ from 'jquery' ;
//import data from '../data.json';
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router';
import {FullBlog} from './FullBlog.js';
import {Author} from './Author.js'
class ExpenseApp extends React.Component{
constructor(props){
super(props);
this.state={
data:this.props.data,
list:[]
}
}
render(){
var data=this.state.data;
var list=this.state.list;
var len= Object.keys(data).length;
for(var i=0;i<len;i++){
//console.log(data[i]);
list.push(<Author key={i} i={i} data={data[i]}/>);
}
return(
<div>
{list}
</div>
)
}
}
module.exports={
ExpenseApp:ExpenseApp
}
the Author.js is like this
import React from 'react';
import ReactDom from 'react-dom' ;
import $ from 'jquery' ;
//import data from '../data.json';
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router';
import {FullBlog} from './FullBlog.js'
class Author extends React.Component{
constructor(props){
super(props);
this.state={
data:this.props.data,
load:false,
content:'',
Author:'',
Book:''
}
this.loadBlog=this.loadBlog.bind(this);
}
loadBlog(i){
var that=this;
var data=this.state.data[i];
that.setState({
// load:true,
Content:this.props.data.Content,
})
that.context.Router.transitionTo(null,'/fullblog');
}
render(){
if(this.state.load===false){
return(
<div onClick={this.loadBlog} >
<div>{this.props.data.Author}</div>
<div>{this.props.data.Book}</div>
</div>
)
}//else{
// return(<Link to="/fullblog"><FullBlog data={this.state.data}/></Link>)
// }
}
}
Author.contextTypes = {
Router: function contextType() {
return React.PropTypes.func.isRequired;
}
};
module.exports={
Author:Author
}
And then there is FullBlog.js
class FullBlog extends React.Component{
render(){
return(<div>Hello world</div>)
}
}
module.exports={
FullBlog:FullBlog
}
And the error that I am getting is
But through this, I am not able to navigate to anything.I am using React-router for the first time and I dont know what the issue is. Thanks

You should use react routers withRouter() higher order function. You pass in your component and withRouter adds a router object to your component props.
import { withRouter } from 'react-router-dom';
// ...
export default withRouter(Author)
Then instead of calling Router.transitionTo (I'm not sure thats a thing) you would call this.props.router.history.push('/somepath')

Related

Reactjs How i can pass props from index.html to App component with Typescript

Hello i want to pass props from index.html to App.tsx as you see i'm using typescript. so i want to do it with typescript.
my code
//index.html
<div id="root" name="test"></div> //props name test
//Index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
var container =document.getElementById('root');
ReactDOM.render(
<App name={container.getAttribute('name')} />
,
container
);
serviceWorker.unregister();
//i'm sorry i should have provided this my knowledge about typescript is very low
//App.tsx
import React from 'react';
import logo from './logo.svg';
import './App.css';
class App extends React.Component {
render(){
return (
<div className="App">
<p>{this.props.name}</p>
</div>
)
}
}
export default App;
You should add props to your App component constructor:
class App extends React.Component {
constructor(props) {
super(props);
}
render(){

Why I can not see results of routing in React?

I have this code, and it is very good working on other environment without webpack.
This is main.js on frontend
import ReactDOM from "react-dom";
import React from "react";
//import { Router, Route, hashHistory } from 'react-router';
import { BrowserRouter, Route } from "react-router-dom";
import App from "./components/App.jsx";
import WizardIndex from "./components/index.js";
ReactDOM.render(
<BrowserRouter>
<App>
<Route path="/signup" component={WizardIndex} />
</App>
</BrowserRouter>,
document.getElementById("mount-point")
);
This is App.jsx
import React from "react";
import { Link } from "react-router-dom";
class App extends React.Component {
render() {
const { children } = this.props;
return (
<div className="App">
<div className="menu-bar">
<div className="menu-item">
<h3>App</h3>
<Link to="/signup">Signup</Link>
</div>
<div className="content">{children}</div>
</div>
</div>
);
}
}
export default App;
And Here I include WizardIndex file index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { Values } from "redux-form-website-template";
import store from "./store";
import showResults from "./showResults";
import WizardForm from "./WizardForm";
class WizardIndex extends React.Component {
render() {
return (
<h1>
Hello!!!React Router
</h1>
);
}
}
export default WizardIndex;
I see Signup link - button on the localhost:8050 But, Why
Why I can not see nothing after I press Signup button
I didnt have any error No in console webpack (there is all green ) Not in console of browser And when I reload the page localhost:8050/signup I get this note in browser but not in consol Cannot GET /signup

You should not use <Route> or withRouter() outside a <Router>

I have wrapped my index.js file to support a Redux Store and React-Router-v4.
However, when I try to run a basic test, I get the following error message:
Invariant Violation: You should not use <Route> or withRouter() outside a <Router>
Here is what my index.js looks like:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
import registerServiceWorker from './registerServiceWorker';
// Redux
import { Provider } from 'react-redux';
import store from "./store/index";
ReactDOM.render((
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
), document.getElementById('root'));
registerServiceWorker();
and here is my App.js:
import React, { Component } from 'react';
import { ScaleLoader } from 'react-spinners';
import { withRouter } from 'react-router';
import Header from './components/Header';
import Footer from './components/Footer';
import Main from './Main';
import './styles/styles.scss';
// Redux
import { connect } from 'react-redux';
import store from "./store/index";
import { isLoading } from "./actions/index";
class App extends Component {
constructor() {
super();
store.dispatch(isLoading(true));
}
componentDidUpdate(prevProps) {
if (this.props.location.pathname !== prevProps.location.pathname) {
store.dispatch(isLoading(true));
}
}
render() {
return (
<div className='App'>
<Header />
<div className='App__wrapper'>
<div className={'loading-spinner ' + (this.props.isLoading ? null : '--hide-loader')}>
<ScaleLoader
color={'#123abc'}
loading={this.props.isLoading}
/>
</div>
<Main />
</div>
<Footer />
</div>
);
}
}
const mapStateToProps = (state) => ({ isLoading: state.isLoading });
export default withRouter(connect(mapStateToProps)(App));
Since I'm using withRouter to wrap for navigation, is this method discouraged? Should I be setting up withRouter at the index.js level?
Thank you!
Try importing your BrowserRouter like this:
import { BrowserRouter as Router } from 'react-router-dom'
Then replace everywhere it appears BrowserRouter with Router instead.

passing parameters through react-router

I have a code which displays four images and when one image is clicked out of those, it takes up the whole screen.I am using react router to implement the same.
The code is like this
App.js
import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import {FirstPage} from './FirstPage.js';
import {Panorama} from './Panorama.js';
import {BrowserRouter,Route,Router,Switch} from 'react-router-dom';
class App extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<div>
<BrowserRouter>
<Switch>
<Route path="/" component={FirstPage} />
<Route path="/image/:id" component={Panorama} />
</Switch>
</BrowserRouter>
</div>
)
}
}
ReactDOM.render(<App/>,document.getElementById('container'));
FirstPage.js
import React from 'react';
import ReactDom from 'react-dom' ;
import $ from 'jquery' ;
import {Panorama} from './Panorama.js';
import {Redirect} from 'react-router-dom';
class FirstPage extends React.Component{
constructor(props){
super(props);
this.state={
list:[],
images:[],
isClicked:false,
redirect:true
}
this.loadImages=this.loadImages.bind(this);
this.loadOne=this.loadOne.bind(this);
}
componentDidMount(){
window.addEventListener('load',this.loadImages);
}
loadImages(){
console.log("load");
var that=this;
$.ajax({
type:'GET',
url:'https://demo0813639.mockable.io/getPanos',
datatype:'jsonp',
success:function(result){
var images=that.state.images;
for(var i=0;i<result.length;i++){
that.state.images.push({"pano":result[i].pano,"name":result[i].name});
}
that.setState({
images:images
})
}
})
}
loadOne(pano){
this.setState({
isClicked:true,
imageUrl:pano
})
}
render(){
var list=this.state.list;
return this.state.isClicked?<Redirect to={'/image/${this.state.imageUrl}'}/>:
<div> {this.state.images.map((result)=>{
return(<div className="box">
<div className="label">{result.name}</div>
<img src={result.pano} className="image col-md-3" onClick={this.loadOne.bind(this,result.pano)}/>
</div>
)
})}
</div>
}
}
module.exports={
FirstPage:FirstPage
}
Panorama.js
import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import {Link} from 'react-router-dom';
class Panorama extends React.Component{
render(){
return(
<div>
<div className="pano">
<img id="myImage" src={props.match.params.id} />
<div className="goback"><Link to="/">Go back</Link></div>
</div>
)
}
}
module.exports={
Panorama:Panorama
}
With this the URL becomes something like this
http://localhost:8080/image/$%7Bthis.state.imageUrl%7D
after clicking on an image and nothing comes up on the screen.With this,
Redirect to={{pathname='/image',params:{this.state.imageUrl}}}
I get syntax errors
What is the correct way of doing this?
It looks like you are using single quotes instead of back-ticks to produce the string inside your to prop.
Try changing
<Redirect to={'/image/${this.state.imageUrl}'}/>
to:
<Redirect to={`/image/${this.state.imageUrl}`}/>
are you using react-router 3 i recommend you to use redirect function provided by react-router 3, that is this.context.router.push() to start redirect.
sample code in component :
class FirstPage extends React.Component{
constructor(context)
{
super(context)
}
...
}
FirstPage.contextTypes = {
router: PropTypes.object.isRequired
}
sample redirect action in react-router 3 :
this.context.router.push({ pathname: `/image${this.state.imageUrl}`})
sample redirect action in react-router 4 :
this.context.router.history.push({ pathname: `/image${this.state.imageUrl}`})

Why I cannot get props from the Provider by mobx-react

I am tring to use the Mobx to manage my react-project's state,but I cannot get the props from the Provider by mobx-react.
This is my root element(I delete the router to simplify the question):
import React from "react";
import ReactDOM from "react-dom";
import {Router, Route, hashHistory} from "react-router";
import {Provider} from "mobx-react";
import store from "../store";
import App from "./app";
ReactDOM.render((
<Provider store={store}>
<App/>
</Provider>),
document.getElementById("content"));
and this is my childNode:
import React, {Component} from "react";
import {observer, inject, PropTypes} from "mobx-react";
#inject("store") #observer
export default class App extends Component {
constructor(props) {
super(props);
console.log(this.props.store);
}
render() {
return (
<div>
ab
</div>
)
}
}
App.propTypes = {
store: PropTypes.observableObject
};
But when I log the store,the result is undefined, and I don't know why I cannot get the store.
From the chrome devtools, I find the Provider has the store but App cannot get store,I am very confused.
My store is bellow:
import {observable} from "mobx";
class Store {
#observable count;
constructor() {
this.count = 1;
}
addCount() {
this.count += 1;
}
decreaseCount() {
this.count -= 1;
}
}
let store = new Store();
export default store;

Categories

Resources