I am new to react and I am trying to send data from my parent component "Dashboard" to a child component "AddData". I know the syntax to do this normally, but what is the syntax to do this when a child is connected to parent through Route?
Shown below is my Dashboard.jsx:
import {withStyles} from '#material-ui/core'
import CssBaseline from '#material-ui/core/CssBaseline'
import PropTypes from 'prop-types'
import * as React from 'react'
import {Route} from 'react-router-dom'
import {Home} from './scenes/home'
import {A} from './scenes/a'
import {B} from './scenes/b'
import {AddData} from '../adddata'
import {VisualizeData} from '../visualizedata'
import {Header} from './components/header'
import {Sidebar} from './components/sidebar'
import styles from './Dashboard.styles'
class Dashboard extends React.Component {
constructor() {
super();
this.state = {
trainPercentageDashboard : "null",
featuresDashboard : [],
labelsDashboard : [],
}
}
render() {
const {classes} = this.props
console.log(window.location.href);
var url_ = new URL(window.location.href);
console.log(url_);
return (
<div className={classes.root}>
<CssBaseline/>
{url_.pathname !== '/neuralnet' &&
<Header/>
}
<Sidebar/>
<main className={classes.content}>
{url_.pathname !== '/neuralnet' &&
<div className={classes.toolbar}/>
}
<Route path="/adddata" component={AddData}/>
<Route exact path="/visualize" component={VisualizeData} />
<Route exact path='/home' component={Home}/>
<Route exact path='/neuralnet' component={A}/>
<Route exact path='/b' component={B}/>
<Route exact path='/' component={B}/>
</main>
</div>
)
}
}
Dashboard.propTypes = {
classes: PropTypes.object.isRequired,
theme : PropTypes.object.isRequired,
}
export default withStyles(styles, {withTheme: true})(Dashboard)
I went through this, but this was not mentioned in it.
Try this:
<Route
path='/adddata'
render={(props) => <AddData {...props} someotherprop={someotherprop} />}
/>
Note that the passed prop can be a part of the state as well. So you can pass the state as this.state.someotherprop.
If you want to pass data down to a component using react router, you can change your Route component to look like this.
<Route
path="/adddata"
render={(props) => (<AddData {...props}>)}
/>
This is a good article on explaining why to use render rather than component but the gist of it is that it is for performance.
You can pass data from parent component using react-router, is very simple
update your code with this, and your issue will be fixed
import {withStyles} from '#material-ui/core'
import CssBaseline from '#material-ui/core/CssBaseline'
import PropTypes from 'prop-types'
import * as React from 'react'
import {Route} from 'react-router-dom'
import {Home} from './scenes/home'
import {A} from './scenes/a'
import {B} from './scenes/b'
import {AddData} from '../adddata'
import {VisualizeData} from '../visualizedata'
import {Header} from './components/header'
import {Sidebar} from './components/sidebar'
import styles from './Dashboard.styles'
class Dashboard extends React.Component {
constructor() {
super();
this.state = {
trainPercentageDashboard : "null",
featuresDashboard : [],
labelsDashboard : [],
name:'rizwan',
}
}
render() {
const {classes} = this.props
console.log(window.location.href);
var url_ = new URL(window.location.href);
console.log(url_);
return (
<div className={classes.root}>
<CssBaseline/>
{url_.pathname !== '/neuralnet' &&
<Header/>
}
<Sidebar/>
<main className={classes.content}>
{url_.pathname !== '/neuralnet' &&
<div className={classes.toolbar}/>
}
<Route
path="/adddata"
component={AddData}
currentStep={this.state.name} />
<Route exact path="/visualize" component={VisualizeData} />
<Route exact path='/home' component={Home}/>
<Route exact path='/neuralnet' component={A}/>
<Route exact path='/b' component={B}/>
<Route exact path='/' component={B}/>
</main>
</div>
)
}
}
Dashboard.propTypes = {
classes: PropTypes.object.isRequired,
theme : PropTypes.object.isRequired,
}
export default withStyles(styles, {withTheme: true})(Dashboard)
Now open your child component: "adddata"
and console props
console.log('wao', this.porps)
thanks,
like and vote up
Related
I Try this code to companion tow composts in react using routs but it render blank page
import React from 'react';
import { Routes , Route } from 'react-router-dom';
// import * as BooksAPI from './BooksAPI'
import './App.css';
import SearchBook from './components/SearchBook';
import Main from './components/Main';
class BooksApp extends React.Component {
state = {
showSearchPage: false
}
render() {
return (
<div className="Root">
<Routes>
<Route exact path="/" element={<Main />} />
<Route path="/search" element = {<SearchBook />}/>
</Routes>
</div>
)
}
}
export default BooksApp
when i tried to render the components directly like this
render() {
return (
<div>
<Main />
<SearchBook />
</div>
)
}
it worked fine
It is better to configure all the routes inside the App.js. If your are providing routes inside BooksApp component. Please make sure, you have imported and called the BooksApp component in the App.js.
You need to import BrowserRouter and wrap all routes inside the BrowserRouter as like given below,
import React from 'react';
import { Routes , Route, BrowserRouter as Router } from 'react-router-dom';
// import * as BooksAPI from './BooksAPI'
import './App.css';
import SearchBook from './components/SearchBook';
import Main from './components/Main';
class BooksApp extends React.Component {
state = {
showSearchPage: false
}
render() {
return (
<div className="Root">
<Router>
<Routes>
<Route exact path="/" element={<Main />} />
<Route path="/search" element = {<SearchBook />}/>
</Routes>
</Router>
</div>
)
}
}
export default BooksApp
Goal:
When you write url "https://react-router-with-params-aq6utk.stackblitz.i/test" I would like to display the page test.
Problem:
Is it possble to retrieve the value 'test' and use it at app.js?
Today it doesn't work.
Info:
*Newbie in reactjs
Stackblitz:
https://stackblitz.com/edit/react-uaofyx?file=src%2FApp.js
app.js
import React, { Component } from 'react';
import { HomeComponent } from './Containers/HomeComponent';
import DashboardComponent from './Containers/DashboardComponent';
import ContactComponent from './Containers/ContactComponent';
import { Switch, Route, Link } from 'react-router-dom';
class App extends Component {
constructor() {
super();
this.state = {
name: 'React',
};
}
render() {
console.log(this.props.id);
console.log(this.props);
if (this.props.id === 'test') {
return (
<div>
<Switch>
<Route path="/test" exact component={ContactComponent} />
</Switch>
</div>
);
} else {
return (
<div>
<Switch>
<Route
path="/dashboard/:id"
render={(props) => (
<DashboardComponent {...props} isAuthed={true} />
)}
/>
<Route path="" exact component={HomeComponent} />
</Switch>
</div>
);
}
}
}
export default App;
ContactComponent.js
import React from 'react';
export const ContactComponent = ({ value }) => {
const name = 'CONTACT';
return <h1>{name}</h1>;
};
DashboardComponent.js
import React, { Component } from 'react';
class DashboardComponent extends Component {
constructor(props) {
super(props);
console.log(this.props.match.params.id);
}
render() {
return <div>Hello from dashboard.. ffff</div>;
}
}
export default DashboardComponent;
HomeComponent.js
import React from 'react';
export const HomeComponent = ({ value }) => {
const name = 'rajesh';
return <h1>{name}</h1>;
};
There are some issues with the implementaion of Route. also, you export the ContactComponent without default but you used it in App.js with the default import statement.
The working code:
import React, { Component } from 'react';
import { HomeComponent } from './Containers/HomeComponent';
import DashboardComponent from './Containers/DashboardComponent';
import { ContactComponent } from './Containers/ContactComponent';
import { Switch, Route, Link, BrowserRouter as Router } from 'react-router-dom';
class App extends Component {
render() {
return (
<Router>
<Switch>
<Route path="/test" exact component={ContactComponent} />
<Route
path="/dashboard/:id"
component={(props) => <DashboardComponent {...props} isAuthed={true} />}
/>
<Route path="" exact component={HomeComponent} />
</Switch>
</Router>
);
}
}
export default App;
check the live version on stackblitz
Explanation:
If you export a variable with the default keyword, so you need to import it without {}
const first = 'first'
const second = 'second'
export first
export default second
Now in usage:
import second, {first} from 'myVariables';
Also, your route configuration with react-router-dom will look like this:
<BrowserRouter>
<Switch>
<Route path="/" exact={true} component={Home} />
<Route path="/about" exact={true} component={About} />
<Route path="/contact" exact={true} component={Contact} />
// rest of the routes ...
</Switch>
</BrowserRouter>
Note: Your App.js component is the root component so there aren't any props with it.
I can’t understand why does not go to the page, but simply changes the URL.
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Link, withRouter } from 'react-router-dom'
import classify from 'src/classify'
import defaultClasses from './logo.scss'
import logo from './logo.svg'
class Logo extends Component {
static propTypes = {
classes: PropTypes.shape({
wrapper: PropTypes.string,
logo: PropTypes.string
})
}
render() {
const { classes, history } = this.props
return (
<Link to="/" className={classes.wrapper}>
<img className={classes.logo} src={logo} height="70" alt="" title="" />
</Link>
)
}
}
export default classify(defaultClasses)(Logo)
there is same withwithRouter() history.push
The component don't rendering.
In renderRoutes() i have next path
<Route exact path="/" component={Page} />
renderRoutes() call from App.js(main)
import React from 'react'
import { Switch, Route } from 'react-router-dom'
import Page from '../../Page'
import Journey from 'src/components/Journey'
const renderRoutingError = props => <ErrorView {...props} />
const renderRoutes = () => (
<Switch>
<Route exact path="/" component={Page} />
<Route exact path="/journey/" component={Journey} />
)
export default renderRoutes
use Context
this.props.pushContext({
nav: <Logo />,
background: 'white'
})
You forgot to close your Switch component in renderRoutes.
const renderRoutes = () => (
<Switch>
<Route exact path="/" component={Page} />
<Route exact path="/journey/" component={Journey} />
</Switch> <-- You forgot to close your Switch here.
)
I am trying to navigate through different screens with BottomNavigationAction from material ui and i get this error You should not use <Link> outside a <Router>
Tab.js:
import React from 'react';
import { Link } from 'react-router-dom';
import { withStyles } from '#material-ui/core/styles';
import BottomNavigation from '#material-ui/core/BottomNavigation';
import BottomNavigationAction from '#material-ui/core/BottomNavigationAction';
// icons
import HomeIcon from '#material-ui/icons/Home';
import DashboardIcon from '#material-ui/icons/Dashboard';
import PaymentIcon from '#material-ui/icons/Payment';
import FaceIcon from '#material-ui/icons/Face';
import AtmIcon from '#material-ui/icons/Atm';
const styles = {
root: {
position: 'absolute',
bottom: 0,
width: '100%',
cursor: 'pointer'
},
wrapper: {
minWidth: '0px'
}
};
class Tab extends React.Component {
state = { value: 0 };
handleChange = (event, value) => {
this.setState({ value });
};
render() {
const { classes } = this.props;
const { value } = this.state;
return (
<div>
<BottomNavigation value={value} onChange={this.handleChange} className={classes.root}>
<Link to="/">
<BottomNavigationAction label="Home" value="home" icon={<HomeIcon />} className={classes.wrapper}/>
</Link>
</BottomNavigation>
</div>
);
}
}
export default withStyles(styles)(Tab);
app.js is where i am trying to render the Tab.js so it stays on all the pages! and my routes are also rendered there
App.js
import React, { Component } from 'react';
import {BrowserRouter} from 'react-router-dom';
import Routers from './Routers';
import Tab from './components/Tab';
class App extends Component {
render() {
return (
<div>
<Tab />
<Routers />
</div>
);
}
}
export default App;
routes.js is where i identify routes:
Routes.js
import React from 'react';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import promise from 'redux-promise';
import { Provider } from 'react-redux';
import Home from './components/Home';
import Profile from './components/Profile';
import Login from './components/auth/Login';
import reducers from './reducers';
import configureStore from './store/configueStore';
import {getAuthToken} from './actions/auth';
const store = configureStore();
const Routers = () => (
<Provider store={store}>
<BrowserRouter>
<div>
<Switch>
<Route path='/' component={Home} exact={true}/>
<Route path='/login' component={Login} exact={true}/>
<Route path='/register' component={Login} exact={true}/>
<Route path='/profile' component={Profile} exact={true}/>
</Switch>
</div>
</BrowserRouter>
</Provider>
);
export default Routers;
how to i use link in my Tab.js file and make the redirection happen
and i will love an explanation on why this problem is accruing and how will i be able to fix it with my current file structure.
And is my file structure good? as i am having a different file for my routes and rendering it inside my app.js
Your Link and Routes must all have a Router provider higher up in the tree. Also you must use a single BrowserRouter. You can change your configuration to the following
const Routers = () => (
<div>
<Switch>
<Route path='/' component={Home} exact={true}/>
<Route path='/login' component={Login} exact={true}/>
<Route path='/register' component={Login} exact={true}/>
<Route path='/profile' component={Profile} exact={true}/>
</Switch>
</div>
);
class App extends Component {
render() {
return (
<div>
<Provider store={store}>
<BrowserRouter>
<div>
<Tab />
<Routers />
</div>
</BrowserRouter>
</Provider>
</div>
);
}
}
You don't have <BrowserRouter> parent for the link used in your tab.js file. Make following changes to your App.js file to make your code work:
import React, { Component } from 'react';
import { BrowserRouter } from 'react-router-dom';
import Routers from './Routers';
import Tab from './components/Tab';
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<Tab />
<Routers />
</div>
</BrowserRouter />
);
}
}
export default App;
I think you should wrap in .
For details you can also refer to Key Concepts For React-Router and React-Router With Material-UI
Here is how the router I defined :
import React from 'react';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import PersonsList from './PersonsList';
import Error from './Error'
import Person from './Person'
const Router = () => (
<BrowserRouter>
<Switch>
<Route path="/persons" strict={false} component={PersonsList}/>
<Route path="/persons/:id" component={Person}/>
<Route component={Error}/>
</Switch>
</BrowserRouter>
);
export default Router;
The first route works perfectly.
The problem is that in the PersonsList, when I try to reach the /persons/:id route, I get a blank page.
Here is the code I use for redirection in the PersonsList component :
static propTypes = {
history: PropTypes.object
};
handleRedirection = (aPerson) => {
this.props.history.push(`/persons/${aPerson.id}`);
}
...
{this.state.persons.map(aPerson => (
<React.Fragment key={aPerson.id}>
<div className="row" onClick={this.handleRedirection.bind(this,aPerson)}>
Here is the Person component :
import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';
class Person extends React.Component {
static propTypes = {
match: PropTypes.object
};
constructor(props){
super(props);
console.log('the selected person : ' + this.props.match.params.id);
}
render(){
return(
<div>A person</div>
)
}
}
export default withRouter(Person);
I can see the console.log output but no rendering of the <div>A person</div>.
Question
Why the second route returns a blank content knowing its component's constructor is called? Why the rendering is not processed ?
i try this.props.history.push('/home'); code part but not correct running.
you can see my component codes in the below.
my full component code :
class Full extends Component {
render() {
return (
<div className="app">
<Header/>
<div className="app-body">
<Sidebar {...this.props}/>
<main className="main">
<Breadcrumb/>
<Container fluid>
<Switch>
<Route path="/dashboard" name="Dashboard" component={Dashboard}/>
<Route path="/applications" name="Applications" component={Applications}/>
<Route path="/roles" name="Roles" component={Roles}/>
<Route path="/poc" name="poc" component={Poc}/>
<Redirect from="/home" to="/dashboard"/>
</Switch>
</Container>
</main>
<Aside/>
</div>
<Footer/>
</div>
);
}
}
Dashboard component code :
class Dashboard extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="animated fadeIn">
<div>test</div>
</div>
)
}
}
export default Dashboard;
History Code:
import {createBrowserHistory} from 'history';
export const history = createBrowserHistory();