How to use Forwarding Refs with react-router-dom - javascript

I already understand the concept of Forwarding Refs and react-router-dom. But in this implementation, I'm not sure how to use it correctly.
I have a child component, where there is a function that set null in a useState.
I want this function to be executed every time I click on the menu item that renders this child component.
This menu is mounted in the com List and the Router in the App, as shown in the 3 files below.
Precisely, I don't know where to put the useRef to execute the child function resetMyState, if it's in App.js or or AppBarAndDrawer.js and how to do it.
childComponent.js
...
const MeusAnuncios = forwardRef((props, ref) => {
const [myState, setMyState] = useState(null);
function resetMyState(){
setMyState(null)
}
async function chargeMyState() {
await
...
setMyState(values)
...
}
...
AppBarAndDrawer.js
...
const drawer = (
<div>
<div className={classes.toolbar} />
<Divider />
<List>
{[
{ label: "Minha Conta", text: "minhaConta", icon: "person" },
{ label: "Novo Anúncio", text: "novoAnuncio", icon: "queue_play_next" },
{ label: "Meus Anúncios", text: "meusAnuncios", icon: "dvr" },
{ label: "Estatísticas", text: "estatisticas", icon: "line_style" },
{ label: "Faturamento", text: "faturamento", icon: "local_atm" },
{ label: "childComponent", text: "childComponent", icon: "notifications" },
].map(({ label, text, icon }, index) => (
<ListItem
component={RouterLink}
selected={pathname === `/${text}`}
to={`/${text}`}
button
key={text}
disabled={text !=='minhaConta' && !cadCompleto ? true : false}
onClick={() => {click(text) }}
>
<ListItemIcon>
<Icon>{icon}</Icon>
</ListItemIcon>
<ListItemText primary={label.toUpperCase()} />
</ListItem>
))}
</List>
<Divider />
</div>
);
return(
...
{drawer}
...
)
...
App.js
...
export default function App() {
const childRef = useRef();
...
<Router>
<AppBarAndDrawer/>
<Switch>
<Route path="/childComponent">
<childComponent />
</Route>
...
...

The ref you create does need to reside in a common ancestor, i.e. App, so it and a callback can be passed on to children components. The ref to ChildComponent and the callback to the AppBarAndDrawer. Additionally, the ChildComponent will need to use the useImperativeHandle hook to expose out the child's resetMyState handler.
MeusAnuncios
Use the useImperativeHandle hook to expose out the resetMyState handler.
const MeusAnuncios = forwardRef((props, ref) => {
const [myState, setMyState] = useState(null);
function resetMyState(){
setMyState(null);
}
useImperativeHandle(ref, () => ({
resetMyState,
}));
async function chargeMyState() {
await
...
setMyState(values)
...
}
...
});
App
Create a resetChildState callback and pass the ref to the child component and callback to the AppBarAndDrawer component.
export default function App() {
const childRef = useRef();
const resetChildState = () => {
if (childRef.current.resetMyState) {
childRef.current.resetMyState();
}
};
...
<Router>
<AppBarAndDrawer onClick={resetChildState} /> // <-- pass callback
<Switch>
<Route path="/childComponent">
<ChildComponent ref={childRef} /> // <-- pass ref
</Route>
...
</Switch>
...
</Router>
}
AppBarAndDrawer
Consume and call the passed callback.
const AppBarAndDrawer = ({ onClick }) => { // <-- destructure callback
...
const drawer = (
<div>
...
<List>
{[
...
].map(({ label, text, icon }, index) => (
<ListItem
component={RouterLink}
selected={pathname === `/${text}`}
to={`/${text}`}
button
key={text}
disabled={text !=='minhaConta' && !cadCompleto}
onClick={() => {
click(text);
onClick(); // <-- call callback here
}}
>
<ListItemIcon>
<Icon>{icon}</Icon>
</ListItemIcon>
<ListItemText primary={label.toUpperCase()} />
</ListItem>
))}
</List>
...
</div>
);
...
};

Related

Where to declare the handler function in child to get the clicked item details

I want the category details in the parent categoryHandler function
from the child component. I don't know where to place this
props.categoryHandler function in the child component so that when it
is clicked I should get the details to the parent categoryHandler
function.
PARENT COMPONENT:
const categoryHandler = (catg) => {
console.log(catg);
}
<div className="categoryBox">
<Category categories={categories} categoryHandler={() => categoryHandler} />
</div>
CHILD COMPONENT:
export default function Category({ categories }) {
if (categories.length) {
const menu = recursiveMenu(categories);
return menu.map((item, key) => <MenuItem key={key} item={item} />);
} else {
return <div>No Menus</div>
}
}
const MenuItem = ({ item }) => {
const Component = hasChildren(item) ? MultiLevel : SingleLevel;
return <Component item={item} />;
};
const SingleLevel = ({ item }) => {
return (
<ListItem button>
<ListItemText className="category-link child" primary={item.title} />
</ListItem>
);
};
const MultiLevel = ({ item }) => {
const { items: children } = item;
const [open, setOpen] = useState(false);
const handleClick = () => {
setOpen((prev) => !prev);
};
return (
<React.Fragment>
<ListItem button onClick={handleClick}>
<ListItemText className="category-link parent" primary={item.title} />
{open ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={open} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
{children.map((child, key) => (
<MenuItem key={key} item={child} />
))}
</List>
</Collapse>
</React.Fragment>
);
};
Your approach in the code is right, just you have to modify two thing to achieve what you are expecting.
In the parent component you have to modify passing the function as a props like this:
categoryHandler={categoryHandler}
In the child component you have to catch the function while destructuring the props and call in on the both list item with the single item as function parameter:
add the function in props destructuring and pass the function as another props to MenuItem
export default function Category({ categories, categoryHandler }) {
if (categories.length) {
const menu = recursiveMenu(categories);
return menu.map((item, key) => <MenuItem categoryHandler={categoryHandler} key={key} item={item} />);
} else {
return <div>No Menus</div>
}
}
Now again pass the function props to Single And MultiLevel List and call the function on both place:
const MenuItem = ({ item, categoryHandler }) => {
const Component = hasChildren(item) ? MultiLevel : SingleLevel;
return <Component item={item} categoryHandler={categoryHandler} />;
};
const SingleLevel = ({ item, categoryHandler }) => {
return (
<ListItem button onClick={handleClick}>
<ListItemText className="category-link child" primary={item.title} />
</ListItem>
);
};
const MultiLevel = ({ item, categoryHandler}) => {
const { items: children } = item;
const [open, setOpen] = useState(false);
const handleClick = () => {
setOpen((prev) => !prev);
};
return (
<React.Fragment>
<ListItem button onClick={handleClick}>
<ListItemText className="category-link parent" primary={item.title} />
{open ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={open} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
{children.map((child, key) => (
<MenuItem key={key} item={child} />
))}
</List>
</Collapse>
</React.Fragment>
);
};
This solution should work fine!
When you call your function passed as a prop, you can pass data from a child to parent component.
Parent Component:
const categoryHandler = (catg) => {
console.log(catg);
}
<div className="categoryBox">
<Category categories={categories} categoryHandler={categoryHandler} />
</div>
Child Component:
export default function Category(props) {
props.categoryHandler(data);
}
You can need to pass the parameter to the function in your parent component like this:
<Category categories={categories} categoryHandler={categoryHandler} />
You need to pass the prop categoryHandler all the way to the SingleLevel like this:
categoryHandler={categoryHandler}
You can need to add onClick to the ListItem in your SingleLevel component with item parameter like this:
<ListItem button onClick={() => categoryHandler(item)}>
You can take a look at this sandbox for a live working example of this solution.

React Class Component is not changing with the change of its props [duplicate]

react-router-dom v5 and React 16
My loading app component contains:
ReactDOM.render(
<FirebaseContext.Provider value={new Firebase()}>
<BrowserRouter>
<StartApp />
</BrowserRouter>,
</FirebaseContext.Provider>,
document.getElementById("root")
);
I have a route component which contains:
{
path: "/member/:memberId",
component: MemberForm,
layout: "/admin"
},
Admin component:
return (
<>
<div className="main-content" ref="mainContent">
<LoadingComponent loading={this.props.authState.loading}>
<AdminNavbar
{...this.props}
brandText={this.getBrandText(this.props.location.pathname)}
/>
<AuthDetailsProvider>
<Switch>{this.getRoutes(routes)}</Switch>
</AuthDetailsProvider>
<Container fluid>
<AdminFooter />
</Container>
</LoadingComponent>
</div>
</>
)
this.getRoutes in the Switch contains the reference route above.
Now from one of my component pages I can navigate to /member/{memberid} this works fine.
the route loads a component called MemberForm
inside MemberForm I have a row that contains this method:
<Row>
{ this.displayHouseholdMembers() }
</Row>
displayHouseholdMembers = () => {
const householdDetails = this.state.family;
if (householdDetails) {
return householdDetails.map((key, ind) => {
if (key['uid'] != this.state.memberKeyID) {
return (
<Row key={ind} style={{ paddingLeft: '25px', width: '50%'}}>
<Col xs="5">
<Link to={ key['uid'] }>
{ key['first'] + " " + key['last'] }
</Link>
</Col>
<Col xs="4">
{ key['relation'] }
</Col>
<Col xs="3">
<Button
color="primary"
size="sm"
onClick={(e) => this.removeHouseRelation(key)}
>
Remove
</Button>
</Col>
</Row>
);
}
});
}
};
MemberForm:
in componentDidMount I do an firebase call to check for the data pertaining to the user using the uid aka memberId in the URL.
class MemberForm extends React.Component {
constructor(props) {
super(props);
this.state = {
...INITIAL_STATE,
currentOrganization: this.props.orgID,
householdRelation: ['Spouse', 'Child', 'Parent', 'Sibling'],
householdSelected: false,
};
}
componentDidMount() {
let urlPath, personId;
urlPath = "members";
personId = this.props.match.params.memberId;
// if it is a member set to active
this.setState({ statusSelected: "Active" })
this.setState({ memberSaved: true, indiUid: personId });
// this sets visitor date for db
const setVisitorDate = this.readableHumanDate(new Date());
this.setState({ formType: urlPath, visitorDate: setVisitorDate }, () => {
if (personId) {
this.setState({ memberSaved: true, indiUid: personId });
this.getIndividualMemberInDB(
this.state.currentOrganization,
personId,
this.state.formType,
INITIAL_STATE
);
}
});
}
...
return (
<>
<UserHeader first={s.first} last={s.last} />
{/* Page content */}
<Container className="mt--7" fluid>
<Row>
...
<Row>
{ this.displayHouseholdMembers() }
</Row>
</Form>
</CardBody>
) : null}
</Card>
</Col>
</Row>
<Row>
<Col lg="12" style={{ padding: "20px" }}>
<Button
color="primary"
onClick={e => this.submitMember(e)}
size="md"
>
Save Profile
</Button>
{ this.state.indiUid ? (
<Button
color="secondary"
onClick={e => this.disableProfile()}
size="md"
>
Disable Profile
</Button>
) : null }
</Col>
</Row>
</Container>
</>
);
When I click on the Link it shows the url has changed 'members/{new UID appears here}' but the page does not reload. I believe what's going on is that since it's using the same route in essence: path: "/member/:memberId"it doesn't reload the page. How can I get it to go to the same route but with the different memberId?
You are correct that the MemberForm component remains mounted by the router/route when only the path param is updating. Because of this the MailForm component needs to handle prop values changing and re-run any logic depending on the prop value. The componentDidUpdate is the lifecycle method to be used for this.
Abstract the logic into a utility function that can be called from both componentDidMount and componentDidUpdate.
Example:
getData = () => {
const urlPath = "members";
const { memberId } = this.props.match.params;
// this sets visitor date for db
const setVisitorDate = this.readableHumanDate(new Date());
this.setState(
{
// if it is a member set to active
statusSelected: "Active",
memberSaved: true,
indiUid: memberId,
formType: urlPath,
visitorDate: setVisitorDate
},
() => {
if (memberId) {
this.setState({ memberSaved: true, indiUid: memberId });
this.getIndividualMemberInDB(
this.state.currentOrganization,
memberId,
this.state.formType,
INITIAL_STATE
);
}
}
);
}
The lifecycle methods:
componentDidMount() {
this.getData();
}
componentDidUpdate(prevProps) {
if (prevProps.match.params.memberId !== this.props.match.params.memberId) {
this.getData();
}
}
For react-router-dom v6, can you try with simple routing? Create a Test.js with
const Test = ()=> <h1>Test Page</h1>
Then, create a Home.js with
const Home = ()=> <Link to="/test">Test</Link>
Then, add them to route.
<BrowserRouter>
<Routes>
<Route path="/" element={<Home/>} />
<Route path="/test" element={<Test />} />
</Routes>
</BrowserRouter>
Does your component structure look like this? For index route, look more at https://reactrouter.com/docs/en/v6/getting-started/overview.

Material-ui Tab clicking submit to go to the next page removes the tab. How can I fix this?

I have these tabs to go to the next step. However, once clicking submits, this will go to the correct page, but this will also remove the tab. How can I fix this?
I have recreated this in codesandbox: https://codesandbox.io/s/dawn-cloud-uxfe97?file=/src/App.js
function TabPanel(props) {
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Box sx={{ p: 3 }}>
<Typography component="span">{children}</Typography>
</Box>
)}
</div>
);
}
TabPanel.propTypes = {
children: PropTypes.node,
index: PropTypes.number.isRequired,
value: PropTypes.number.isRequired
};
function a11yProps(index) {
return {
id: `simple-tab-${index}`,
"aria-controls": `simple-tabpanel-${index}`
};
}
const Ordering = () => {
const [value, setValue] = React.useState(0);
const handleChange = (event, newValue) => {
setValue(newValue);
};
return (
<div>
<Box sx={{ borderBottom: 1, borderColor: "divider" }}>
<Tabs
value={value}
onChange={handleChange}
aria-label="basic tabs example"
>
<Tab
label="Step 1"
{...a11yProps(0)}
component={Link}
to={`/step1`}
/>
<Tab label="Step 2" {...a11yProps(1)} />
</Tabs>
</Box>
<TabPanel value={value} index={0}>
<Step1 />
</TabPanel>
<TabPanel value={value} index={1}>
<Step2 />
</TabPanel>
</div>
);
};
export default Ordering;
Step1.js
Navigating this to the step2 component does go to the next page, but this will also remove the tab
import { useNavigate } from "react-router-dom";
const Step1 = () => {
const navigate = useNavigate();
const handleSubmit = (e) => {
e.preventDefault();
navigate("/Step2");
};
return (
<div>
<form onSubmit={handleSubmit}>
<input type="submit" />
</form>
</div>
);
};
export default Step1;
Step2.js
const Step2 = () => {
return <div>Step2</div>;
};
export default Step2;
In your case you're not nesting your routes properly. So, For nested route you need to define a route inside another one. Refer this page https://reactrouter.com/docs/en/v6/api#routes-and-route for more information.
Getting back to your question. You need to update your code in two place. First how the routes are defined.
<Route path="/page" element={<Page />}>
<Route path="step1" element={<Step1 />} />
<Route path="step2" element={<Step2 />} />
</Route>
Once, your routes are updated. You are linking your panels based on route. So, you need not define them again in your Page component. You can remove those component from there and just add code so that when tab is click you change your navigation bar url. Sadly Tab of mui doesn't support component property https://mui.com/api/tab/ . You have to do that manually. You can use useNavigate provided by react router dom. Your updated Page component would look like this
I have added comment // This is added. To see where I've made changes. Just in 2 places changes are required.
import React, { useState, useEffect } from "react";
import { Box, Tab, Typography, Tabs } from "#mui/material";
import PropTypes from "prop-types";
import Step1 from "./Step1";
import Step2 from "./Step2";
import { Link } from "react";
// hook is imported
import { useNavigate } from "react-router-dom";
function TabPanel(props) {
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Box sx={{ p: 3 }}>
<Typography component="span">{children}</Typography>
</Box>
)}
</div>
);
}
TabPanel.propTypes = {
children: PropTypes.node,
index: PropTypes.number.isRequired,
value: PropTypes.number.isRequired
};
function a11yProps(index) {
return {
id: `simple-tab-${index}`,
"aria-controls": `simple-tabpanel-${index}`
};
}
const paths = ['/page/step1', '/page/step2']
const Ordering = () => {
const [value, setValue] = React.useState(0);
//This is added
const navigate = useNavigate()
const handleChange = (event, newValue) => {
setValue(newValue);
// This is added
navigate(paths[newValue])
};
return (
<div>
<Box sx={{ borderBottom: 1, borderColor: "divider" }}>
<Tabs
value={value}
onChange={handleChange}
aria-label="basic tabs example"
>
<Tab
label="Step 1"
{...a11yProps(0)}
component={Link}
to={`/step1`}
/>
<Tab label="Step 2" {...a11yProps(1)} />
</Tabs>
</Box>
{/* Removed tab panels from here */}
</div>
);
};
export default Ordering;

state do not change with useContext

hello
I am trying to make a menu toggle, where I have a variable with false as initial value, using react createContext and useContext hook, I set the initial state as true
// useMenu Context
import React, { useContext, useState } from 'react'
export const useToggle = (initialState) => {
const [isToggled, setToggle] = useState(initialState)
const toggle = () => setToggle((prevState) => !prevState)
// return [isToggled, toggle];
return { isToggled, setToggle, toggle }
}
const initialState = {
isMenuOpen: true,
toggle: () => {},
}
export const MenuContext = React.createContext(initialState)
const MenuProvider = ({ children }) => {
const { isToggled, setToggle, toggle } = useToggle(false)
const closeMenu = () => setToggle(false)
return (
<MenuContext.Provider
value={{
isMenuOpen: isToggled,
toggleMenu: toggle,
closeMenu,
}}>
{children}
</MenuContext.Provider>
)
}
export default MenuProvider
export const useMenu = () => {
return useContext(MenuContext)
}
so If true it will show the Menu if false it will show the Div where there a div
App.js
const { isMenuOpen } = useMenu()
//the providder
<MenuProvider>
<Header mode={theme} modeFunc={toggleTheme}/>
{isMenuOpen ? (
<Menu />
) : (
<Switch>
<Route path='/writing' component={Writings} />
<Route path='/meta' component={Meta} />
<Route path='/contact' component={Contact} />
<Route path='/project' component={Project} />
<Route exact path='/' component={Home} />
<Route path='*' component={NotFound} />
</Switch>
)}
<Footer />{' '}
</MenuProvider>
and when I add an onclick event the NavLink button of the menu to close it it does not work
Menu
const { closeMenu } = useMenu()
// return statement
{paths.map((item, i) => {
return (
<MenuItem
key={i}
link={item.location}
svg={item.icon}
path={item.name}
command={item.command}
onClick={closeMenu}
/>
)
})}
where did I go wrong
Issue
I suspect the issue is in App where you've a useMenu hook outside the MenuProvider used in App. This useMenu hook is using a MenuContext context but in the absence of a provider it instead uses the default initial context value.
const initialState = {
isMenuOpen: true,
toggle: () => {},
};
export const MenuContext = React.createContext(initialState);
export const useMenu = () => {
return useContext(MenuContext)
};
React.createContext
const MyContext = React.createContext(defaultValue);
Creates a Context object. When React renders a component that
subscribes to this Context object it will read the current context
value from the closest matching Provider above it in the tree.
The defaultValue argument is only used when a component does not
have a matching Provider above it in the tree. This default value can
be helpful for testing components in isolation without wrapping them.
Solution
Since I doubt you want to run/provide more than one menu provider I believe the solution is to move MenuProvider out of and wrap App to provide the context you are updating by nested components.
App.jsx
const { isMenuOpen } = useMenu();
...
<>
<Header mode={theme} modeFunc={toggleTheme}/>
{isMenuOpen ? (
<Menu />
) : (
<Switch>
<Route path='/writing' component={Writings} />
<Route path='/meta' component={Meta} />
<Route path='/contact' component={Contact} />
<Route path='/project' component={Project} />
<Route exact path='/' component={Home} />
<Route path='*' component={NotFound} />
</Switch>
)}
<Footer />
</>
index.jsx (?)
import App from './App.jsx';
...
//the provider
<MenuProvider>
<App />
</MenuProvider>

React.js history.push in a separate function?

Can you help me with React.js history.push function?
I have a icon which can be pressed. The onClick calls handleRemoveFavourite function which filters out the current item from localStrorage and sets the updated string to storage. This works fine.
After the storage update is done the program should reroute the user to the root page /favourites. The reroute works well in the bottom example. But how to do this in the handleRemoveFavourites function?
This is the code I would like to have
handleRemoveFavourite = () => {
const { name } = this.props.workout;
let savedStorage = localStorage.saved.split(",");
let cleanedStorage = savedStorage.filter(function(e) {
return e !== name;
});
localStorage.setItem("saved", cleanedStorage.toString());
history.push("/favourites")
};
renderHeartIcon = () => {
return (
<Route
render={({ history }) => (
<Rating
icon="heart"
defaultRating={1}
maxRating={1}
onClick={this.handleRemoveFavourite}
/>
)}
/>
);
};
The rerouting works fine with just this:
renderHeartIcon = () => {
return (
<Route
render={({ history }) => (
<Rating
key={1}
icon="heart"
defaultRating={1}
maxRating={1}
size="large"
onClick={() => history.push("/favourites")}
/>
)}
/>
);
};
The whole component looks like this:
import React from "react";
import {
Container,
Grid,
Icon,
Label,
Table,
Header,
Rating,
Segment
} from "semantic-ui-react";
import { Link, Route } from "react-router-dom";
export default class WorkoutComponent extends React.PureComponent {
renderChallengeRow = workouts => {
let { reps } = this.props.workout;
reps = reps.split(",");
return workouts.map((item, i) => {
return (
<Table.Row key={item.id}>
<Table.Cell width={9}>{item.name}</Table.Cell>
<Table.Cell width={7}>{reps[i]}</Table.Cell>
</Table.Row>
);
});
};
handleRemoveFavourite = () => {
const { name } = this.props.workout;
let savedStorage = localStorage.saved.split(",");
let cleanedStorage = savedStorage.filter(function(e) {
return e !== name;
});
localStorage.setItem("saved", cleanedStorage.toString());
// history.push("/favourites");
};
renderHeartIcon = () => {
return (
<Route
render={({ history }) => (
<Rating
key={1}
icon="heart"
defaultRating={1}
maxRating={1}
size="large"
onClick={this.handleRemoveFavourite}
/>
)}
/>
);
};
render() {
const { name, workouts } = this.props.workout;
const url = `/savedworkout/${name}`;
return (
<Grid.Column>
<Segment color="teal">
<Link to={url}>
<Header as="h2" to={url} content="The workout" textAlign="center" />
</Link>
<Table color="teal" inverted unstackable compact columns={2}>
<Table.Body>{this.renderChallengeRow(workouts)}</Table.Body>
</Table>
<br />
<Container textAlign="center">
<Label attached="bottom">{this.renderHeartIcon()}</Label>
</Container>
</Segment>
<Link to="/generate">
<Icon name="angle double left" circular inverted size="large" />
</Link>
</Grid.Column>
);
}
}
Since you are using react-router you can use withRouter to achive this.
import { withRouter } from 'react-router-dom'
Wrap the with class name with withRouter.
Like this:
instead of doing like this:
export default class App .....
Separate this like:
class App ...
At the end of the line:
export default withRouter(App)
Now you can use like this:
handleRemoveFavourite = () => {
const { name } = this.props.workout;
let savedStorage = localStorage.saved.split(",");
let cleanedStorage = savedStorage.filter(function(e) {
return e !== name;
});
localStorage.setItem("saved", cleanedStorage.toString());
this.props.history.push("/favourites");
};
You can remove Route from renderHearIcon():
renderHeartIcon = () => {
return (
<Rating
key={1}
icon="heart"
defaultRating={1}
maxRating={1}
size="large"
onClick={this.handleRemoveFavourite}
/>
);
};
onClick={this.handleRemoveFavourite}
=>
onClick={()=>this.handleRemoveFavourite(history)}
handleRemoveFavourite = () => {
=>
handleRemoveFavourite = (history) => {
The problem you are facing is, you are providing <Route> with the history prop, so that it is propagated on the component function call. But you are not propagating it to the handleRemoveFavourite function.
You'll need to wrap this. handleRemoveFavourite in an anonymous function call. Like
onClick={() => this.handleRemoveFavourite(history)}
and then accept it as a valid argument in your function
handleRemoveFavourite = (history) => {...}
that should solve it
Changing to this.props.history.push("/favourites"); should works.
EDITED
Is your component inside a Route? If so, this.props.history will works. I tested changing your class to run on my project.
import React from 'react';
import ReactDOM from 'react-dom';
import {
Container,
Grid,
Icon,
Label,
Table,
Header,
Rating,
Segment
} from "semantic-ui-react";
import { Link, Route, BrowserRouter as Router } from "react-router-dom";
export default class WorkoutComponent extends React.Component {
static defaultProps = {
workout: {
reps: "1,2,3,4",
workouts: []
},
}
renderChallengeRow = workouts => {
let { reps } = this.props.workout;
reps = reps.split(",");
return workouts.map((item, i) => {
return (
<Table.Row key={item.id}>
<Table.Cell width={9}>{item.name}</Table.Cell>
<Table.Cell width={7}>{reps[i]}</Table.Cell>
</Table.Row>
);
});
};
handleRemoveFavourite = () => {
const { name } = this.props.workout;
//let savedStorage = localStorage.saved.split(",");
// let cleanedStorage = savedStorage.filter(function(e) {
// return e !== name;
// });
// localStorage.setItem("saved", cleanedStorage.toString());
this.props.history.push("/favourites");
};
renderHeartIcon = () => {
return (
<Route
render={({ history }) => (
<Rating
key={1}
icon="heart"
defaultRating={1}
maxRating={1}
size="large"
onClick={this.handleRemoveFavourite}
/>
)}
/>
);
};
render() {
console.log(this.props)
const { name, workouts } = this.props.workout;
const url = `/savedworkout/${name}`;
return (
<Grid.Column>
<Segment color="teal">
<Link to={url}>
<Header as="h2" to={url} content="The workout" textAlign="center" />
</Link>
<Table color="teal" inverted unstackable compact columns={2}>
<Table.Body>{this.renderChallengeRow(workouts)}</Table.Body>
</Table>
<br />
<Container textAlign="center">
<Label attached="bottom">{this.renderHeartIcon()}</Label>
</Container>
</Segment>
<Link to="/generate">
<Icon name="angle double left" circular inverted size="large" />
</Link>
</Grid.Column>
);
}
}
ReactDOM.render(
<Router>
<Route path="/" component={ WorkoutComponent }/>
</Router>, document.getElementById('root'));

Categories