React dynamically create routes - arrays

First things first is this possible to have 2 components on a page one displaying simple static markup but the second one in my parent is going to be a div that displays a link for each item in an array and if you click on it at the bottom of the div then data will be displayed for each one?
If this is possible are dynamic props as simple as performing .map inside the element and printing out a route?
Will also add that I am receiving the following on my Router object but I installed react-router globally though it is also in my node_modules folder.
'react-router' does not contain an export named 'hashHistory'.
import React, { Component } from 'react';
import { Router, Route, IndexRoute, hashHistory } from "react-router";
class DetailsComponent extends Component {
render() {
return (
<Router history={hashHistory}>
// in here will map this.props.data and for each one print a route
// the component for that route will be a DetailedViewComponent that
// that takes in the data in the props and renders it
// so i might need a link? in this render method aswell?
</Router>
);
}
}
export default DetailsComponent ;

React Router match params can be used to render content dynamically
ie. <Route path="/dynamicroute/:id" component={DynamicComponent}/> will provide an id param that can be retrieved via props.match.params inside <DynamicComponent/>

Spoke to some more senior react developers and they said what I was after was npm package Component-Router I haven't got back onto the project just yet but will post full code once completed :)

Related

How do I change the styles of some shared component in React and I have configured routes with react route

I am working on a web app that is consisted of few pages and have configured routes with react-route-dom. On the pages, I have some shared components and I want them to be styled differently on other pages except the Home page.
How do I get this done? Any help?
Thanks
Check if pathname is path of home or else not you can use useLocation to get the pathname and add conditional styling or classes.
useLocation v5
useLocation v6
import React from 'react';
import {useLocation} from 'react-router-dom';
export const Common_Component=()=>{
const location=useLocation()
const pathname=location.pathname
return(
<div>
<div classes={pathname=="home"?"home_class":"other_class"}>
...
</div>
</div>
)
}
Or
You can pass boolean props to the component to let component know it should use home bases classes or other classes.
PS.
you will still need to do conditional check if props is true or false
useMatch you can use useMatch to match the current url with regex.
While it is always good to share code, I would recommend creating a new component for the homepage. Otherwise you are coupling your components. What happens if you want to add another specialisation for the whatever-component? You add another case! Your components grow and wire up more and more until you have one big pot of spaghetti. Hence, it makes sense in many situations to just create a new component for a new use-case.

React doesn't render on page refresh or manual URL entry

I've made two components. one is Articles.js and the another one is article.js. The router is in app.js. here is code from app.js:
<Router>
<Switch>
<Route exact path="/articles" component={Articles}>
</Route>
<Route path="/article/:id" component={Article}/>
</Switch>
</Router>
I've made link to "article/:id" in Articles component. If I click on the link in articles page, it works just fine, however, If I try to reload the page or manually enter id, for eg: "article/23", it will not render anything at all on the page.
I found some results on internet, but, most of them are either not relevant or are using hooks, which I cannot use with class components.
In componentDidMount function of Article compnent i am calling getData function which fetches data from the server and then after verfiying the response sends data here to this function :
initFunction = (ar)=>{
let data = ar.map(d=>{
return(
<tr><td>{d.id}</td><td>{d.title}</td><td>{moment(d.created_on).format('MMMM,Do YYYY')}</td><td>
<Link to={`article/${d.id}`}>Edit</Link> |
<Link to={`article/delete/${d.id}`}> Delete</Link>
</td></tr>
)
})
this.setState({
tableData:<>{data}</>
})
}
And this function just generates table rows and save them in state, which I use in render function to display the data. If I go to article page through this link, it will work fine but same link will not render anything if type it manually or reload it.
Here are the components I am importing in my component:
import ReactPaginate from 'react-paginate';
import { Link } from 'react-router-dom';
import { instanceOf } from 'prop-types';
import { withCookies, Cookies } from 'react-cookie';
import moment from 'moment'
The issue here is probably that your server is not set up to serve your app on the /article route.
When you click on the link in your app then react-router does not actually request make a request to your server for that route. Instead it updates the url and re-renders your app which picks up the new route.
When you load the route directly (such as on page reload or manually typing in the url bar) the react router has not been loaded yet. Instead the browser just blindly makes a request to that route. This is when your app is failing.
I had the same issue as you. I found the solution from this thread.
react-router dynamic segments crash when accessed
added into the of my index.html
what is initState of id, I think you need to store id to state and set initState is empty string, it work for me.
const [myId, setMyId] = useState("")

NextJS - Router.push with props for page

In my React app, I've used import Router from 'next/router' to move to another page with: Router.push('/form').
However on form where I have the function component:
export default function FormOnSubmitExample() { ... }
I want to be able to pass some props into it (these have already been gathered on the first page/from where I'm directing from.
How is this possible?
Thanks.

React redirect on click of svg element

I have a single page React App that is d3 and SVG heavy, and I would like to be able to redirect from one page to another when a user clicks on an svg rect on one of my pages. I am familiar with this.props.history.push() as well as the <Link> component from the react-router-dom library, however neither of these seem to help in this instance.
The svg element of relevance here is deep in a graphing component of mine that is 3-4 children down from the front-end's main App.js file that does all of the routing, and when I run console.log(this.props) in my component with the svg, there is no history object on the props. I'm not sure if a reproducible example is needed here, as I just need direction.
In short, I have no idea what should go into the on-click function that is associated with my svg rect, to enable redirect in my app. Any thoughts on this would be greatly appreciated!
Edit: obviously this is wrong but i tried to return a Redirect component in on-click handler and it didn't work:
...
...
function handleMouseClick() {
console.log('clicked')
return <Redirect to='/stats' />;
}
myRect.on('click', handleMouseClick)
...
Edit2: should i put the rect elements inside of components in the svg? is that even possible?
You can add the history prop from react-router to a component by wrapping it with withRouter. Just make sure whatever is mounting your component is using the wrapped version (usually by only exporting the wrapped component).
import React from 'react';
import { withRouter } from 'react-router';
class MyComponent extends React.Component {
render() {
return (
<button onClick={() => this.props.history.push('/newpage')}>
Click me
</button>
);
}
}
export default withRouter(MyComponent);

Is it possible to change route on scroll?

I want to load multiple components on a single page and have different routes for all of them. For example i hit a route /article/1 and it loads a component, after scrolling through completely through that article i want the route to change to /article/2 and the corresponding article to load. I am using react and react router, basically i want 4 (article/3 , article/4) articles on a page and all these should be scrollable with the route changing as i scroll onto a particular article. How can i achieve this using react and react-router?
use react-perfect-scrollbar package from npm.
index.js (main entry point of your application) add this css
import 'react-perfect-scrollbar/dist/css/styles.css';
your component file where you want on scroll change url
import PerfectScrollbar from 'react-perfect-scrollbar';
import { Redirect } from 'react-router-dom';
handleScroll = () => {
<Redirect to="/article/2" />
}
<PerfectScrollbar onYReachEnd={this.handleScroll}> // when you reach then end of screen it's call handleScroll function and redirect to other url.so based on your requirements you can pick up from here.
// your articles code..
</PerfectScrollbar>

Resources