render new state in react router - javascript

I'm trying to change the state title value to the value I give in the router, but I do not know why it does not work. This code is compiled, but the title is an empty string all the time.
class Header extends React.Component {
state = {
title: '',
};
updateTitle(title) {
this.setState({ title });
}
render() {
const { title } = this.state;
return (
<Typography>
{title}
</Typography>
<Switch>
<Route
exact
path="/"
render={() => (<DashboardPage updateTitle={this.updateTitle} />)}
title="Dashboard"
/>
<Route
path="/payment"
render={() => (<PaymentPage updateTitle={this.updateTitle} />)}
title="Payment"
/>
</Switch>
)};

You have to bind the Component method to pass .this context. So updateTitle = (title)=> {}

You should wrap this.updateTitle in an arrow function like below. Then you can call updateTitle from DashBoardPage.
<Route
path="/dashboard"
render={() => (<DashBoardPage updateTitle={(title) => this.updateTitle(title)} />)}
title="Dashboard"
/>
For example, your DashBoardPage component could look something like below. By calling updateTitle which we have passed as a prop, we are changing the title in the parent component.
DashBoardPage.js
const DashBoardPage = ({ updateTitle }) => {
updateTitle('paymentPage');
return <div>This is the dashboard page</div>;
};
However, i would strongly advise against doing this. A better approach would be to have a Page component. Then DashBoardPage and PaymentPage return a Page component and pass the title as prop.

Related

Can't pass data from one page to another with React-Router-DOM (useHistory, useLocation)

I have a router:
<Switch>
<Route exact path="/">
<CustomPaddingContainer padding="0 0.5em 1.5em">
<TableViewComponent columns={tableAccessors} />
</CustomPaddingContainer>
</Route>
<Route path="/new-objective">
<AddNewObjectiveComponent onSubmit={onSubmitObjective} onCancel={onCancel} />
</Route>
<Route path="/new-kr">
<AddNewKrComponent onSubmit={onSubmitKR} onCancel={onCancel} />
</Route>
<Route path="/okr-details/:id">
<OkrDetailsWithParams />
</Route>
</Switch>
and I want to pass specific data from specific component to one of this Route when specific button will be clicked. to be more precise, I have this component:
const AddOKRButtons: FC<AddOKRButtonsProps> = ({ parentObjectiveId }) => {
const history = useHistory();
const onAddOkrButtonClick = () => {
history.push('/new-objective', { parentObjectiveId: parentObjectiveId });
};
const onAddKrButtonClick = () => {
history.push('/new-kr', { parentObjectiveId: parentObjectiveId });
};
return (
<OkrDetailsChildrenCardsButtonContainerCentered>
<ButtonGroup>
<LinkButton to="/new-objective" appearance="default" onClick={onAddOkrButtonClick}>
Add a new sub-objective
</LinkButton>
<LinkButton to="/new-kr" appearance="default" onClick={onAddKrButtonClick}>
Add a new key-result
</LinkButton>
</ButtonGroup>
</OkrDetailsChildrenCardsButtonContainerCentered>
);
};
Im trying to pass the **parentObjectiveId** which is coming from props to the /new-objective page or /new-kr page in order what button was clicked. After that Im trying to get that data in component where it should be with useLocation hook:
export const AddNewObjectiveComponent: FC<NonNullable<AddNewOKRProps>> = props => {
const location = useLocation();
console.log(location);
return(<div></div>)
}
and unfortunately i got undefined in the state key, where the data is probably should be:
Try to push history route like
history.push({
pathname: '/new-objective',
state: { parentObjectiveId: parentObjectiveId }
});
I hope it will be work for you. Thanks!

ReactRouterDom, AuthRoute returns react render functions are not valid as react child warning

My Router is a simple component containing public and private routes. I have created an AuthRoute referring to the great tutorial from here
So, my Router looks like:
<Router>
<div>
<Navigation />
<Route exact path={ROUTES.LANDING} component={Landing} />
<Route path={ROUTES.SIGN_UP} component={SignUp} />
<Route path={ROUTES.SIGN_UP_SUCCESS} component={SignUpSuccess} />
<AuthenticationRoute path={ROUTES.HOME} component={Home} />
</div>
</Router>
and my AuthenticationRoute looks like this:
export const AuthenticationRoute = ({ component: Component, ...rest }) => {
const [authChecking, setAuthChecking] = useState(true);
const [{ isAuth }, dispatch] = useStateValue();
useEffect(() => {
checkLoggedIn().then(res => {
setAuthChecking(false);
dispatch({
op: 'auth',
type: 'toggleSessionAuth',
toggleSessionAuth: res
});
});
}, [])
if(authChecking)
return null;
if(!isAuth) {
return <Redirect to='/' />;
}
return <Route {...rest} render={(props) => (
<Component {...props} />
)
} />
}
Everything looks fine, however, my console returns such warning:
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from the render. Or maybe you meant to call this function rather than return it.
I have tried different solutions using component/render etc, however, I could not find a solution to this problem and I have no idea what I am doing wrong.
For testing purposes, instead of rendering Component, I tried to render simple <div>test</div> and it worked fine. However, when I am passing a JSX component in props, it returns the warning shown above.
Implementation oh Home Component (Home.js):
export const Home = () => {
const [{ user }, dispatch] = useStateValue();
const { history } = useReactRouter();
const moveTo = path => {
dispatch({
op: 'other',
type: 'setView',
setView: path
});
history.push(path);
}
return (
<div className="pageMenuWrapper">
<h1 className="homeTitle">Hi {() => user ? `, ${user.username}` : ``}.</h1>
<div className="wrapper">
<Tile image={leagueico} alt="text" onClick={() => moveTo(ROUTES.TEST)}/>
<Tile comingSoon />
</div>
</div>
);
}
export default Home;
Could anyone help me solve this little problem?

react is not recognizing params?

so in react I have an App component that is rendering several child components like this:
App
render() {
return (
//JSX inside
<BrowserRouter>
<div>
<Header />
<Switch>
<Route exact path="/" component={Courses} />
<Route exact path="/courses/create" component={() => <CreateCourse email={this.state.emailAddress} pass={this.state.password} />} />
<Route exact path="/courses/:id/update" component={() => <UpdateCourse email={this.state.emailAddress} pass={this.state.password} />} />
<Route exact path="/courses/:id" component={() => <CourseDetail email={this.state.emailAddress} pass={this.state.password} />} />
<Route exact path="/signin" component={ () => <UserSignIn signIn={this.signIn}/>} /> {/*pass in the signIn() in a prop called signIn to the UserSignIn component*/}
<Route exact path="/signup" component={UserSignUp} />
{/* <Route exact path="/signout" component={UserSignOut} /> */}
</Switch>
</div>
</BrowserRouter>
);
}
In this component I have params so that I am able to see a course by its id:
CourseDetail
componentDidMount() {
const {match: { params }} = this.props; //I used a code snippet from this video https://scotch.io/courses/using-react-router-4/route-params
//fetch data from API
axios
.get(`http://localhost:5000/api/courses/${params.id}`)
.then(results => {
//results param came back as data from api
this.setState({
//set state by setting the courses array to hold the data that came from results
course: results.data,
user: results.data.user
});
//console.log(results); //By console logging I was able to see that I am getting each individual course's info in the data object
});
}
//this method will be for deleting a course
handleDelete() {
const { match: { params }, history } = this.props;
axios.delete(`http://localhost:5000/api/courses/${params.id}`, {
auth: {
username: this.props.email,
password: this.props.pass
}
}).then(() => {
history.push("/"); //I used the history object and have it push to the homepage, that way every time I delete a course I am redirected to (/) afterwards
});
}
the error I am getting when I try to navigate to the CourseDetail component that uses params is:
can someone help?
You need to pass props like this read here
component={props => <CourseDetail {...props} email={this.state.emailAddress} pass={this.state.password} />} />
The props passed to courseDetails component do not have any prop name match and in your componentDidMount you're doing this
const {match: { params }} = this.props;
Here match will be undefined so you can access params
You can understand by this example
let a = {a:{b:1}}
let {x:{b,}} = a
The above code is same as below
"use strict";
var a = {
a: {
b: 1
}
};
var b = a.x.b;
So eventually here if during destructuring if you don't have match as params you're trying to access
(this.props.match).params
|
|__________ This is undefined you end up `undefined.params`
Match is not defined because you didn't pass it down the component as props.
To do that
<Route exact path="/courses/:id/update" component={(routeProps) => <UpdateCourse email={this.state.emailAddress} pass={this.state.password} routeProps = {routeProps} />} />
you can then get your Match property via
routeProps.
const {match} = this.routeProps;
Or simply use the property spread notation which will spread out the properties in routeProps as discrete properties in your component.
Example,
<Route exact path="/courses/:id/update" component={(routeProps) => <UpdateCourse email={this.state.emailAddress} pass={this.state.password} {...routeProps} />} />
This is equivalent to writing-
<Route exact path="/courses/:id/update" component={(routeProps) => <UpdateCourse email={this.state.emailAddress} pass={this.state.password} Match = {this.routeProps.Match} Location = {this.routeProps.Location}/>} History = {this.routeProps.History />
When you write this
const {match: { params }} = this.props;
It means you are expecting props to have a match attribute like below:
params = this.props.match.params;
This is why you are getting the specified error.
If you want to assign a variable the props use this
const params = props;
Note: [If you surround a variable with bracket const {match} = props; it means you are expecting a key match in props.

How pass a prop in my route from my component to a child component with an 'onClick'

I've got a component in my react app with an idTeam.
When I click on a Button, in a child component with an event onClick, I want to pass on my Details page with this idTeam in my props.
Here are my Routes & my Switch:
{/* ... other components ... */}
<Menu.Item
name='details'
active={activeItem === 'details'}
onClick={this.handleItemClick}
>
<Link to="/details">Détails</Link>
</Menu.Item>
</Menu>
</div>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/equipes' component={Teams} />
<Route path='/details/:idTeam' component={Details} />
<Route component={Page404} />
</Switch>
My parent Component:
const teamsComponents = this.state.teamsList.map((team)=> (
<TeamItem
key={team.idTeam}
strTeamBadge={team.strTeamBadge}
strTeam={team.strTeam}
strStadium={team.strStadium}
goToDetails={this.goToDetails(team.idTeam)}
/>
))
And the function goToDetails():
goToDetails = (idTeam) => {
return <Link to={`/details/${idTeam}`} render={(props) => <Details
idTeam={idTeam} {...props} /> } />
}
And the Child Component:
onReceiveDetails = () => {
this.props.goToDetails()
console.log('mes props 2 :' , this.props.params.idTeam);
}
<Button
icon='group'
label={{ as: 'a', basic: true, content: 'Détails',
color:'black' }}
labelPosition='right'
color='black'
onClick={() => this.onReceiveDetails()}
/>
When i'm trying to click on my button i've got "_this.props.goToDetails is not a function"...
Any idea to keep this idTeam on Details Page ?
In your "Parent Component" try passing the goToDetails prop as goToDetails={() => this.goToDetails(team.idTeam)} instead of the way you're currently doing it. This will make sure a function gets passed down to the child component (I assume TeamItem).
Your parent component would then look like:
const teamsComponents = this.state.teamsList.map((team) => (
<TeamItem
key={team.idTeam}
strTeamBadge={team.strTeamBadge}
strTeam={team.strTeam}
strStadium={team.strStadium}
// -> change the line below
goToDetails={() => this.goToDetails(team.idTeam)}
/>
))
Also, in your goToDetails function, you may want to use this.props.history.push(<YOUR-PATH>) like this:
goToDetails = (idTeam) => {
this.props.history.push(`/details/${idTeam}`);
}
<TeamItem
key={team.idTeam}
strTeamBadge={team.strTeamBadge}
strTeam={team.strTeam}
strStadium={team.strStadium}
goToDetails={() => this.goToDetails(team.idTeam)}
/>
))
Your function is invoked when the component renders, try using an arrow function

Can't use props in child component when using Formik for building a wizard

I am trying to build a form-wizard. I set up the wizard via react-router and used formik for the forms. Now I ran into a problem while creating a customizable radio-button. I used the react-custom-radio library for that.
When I use the radio-buttons outside of the routes, it is working as it should (code at the bottom of the post).
When I use the with the router, the props are passed down to the child component:
<Route path="/form/location" render={(props) => (<Pricing {...props} />)} />
Inside the child component, I access the props the same way, as I did it in the parent, where it worked.
const Pricing = (props) => {
const {
values,
touched,
errors,
setFieldValue,
setFieldTouched,
} = props;
return (
<div>
<MyRadio
value={values.car}
onChange={setFieldValue}
onBlur={setFieldTouched}
error={errors.car}
touched={touched.car}
/>
</div>
);
}
But now I always get the error Cannot read property 'car' of undefined.
Why doesn't it work if there's a router in between?
If I do it like that, it works:
<Form>
<Switch>
<Redirect from="/" exact to="/form/location" />
<Route path="/form/location" render={(props) => (<Pricing {...props} />)} />
</Switch>
<MyRadio
value={values.car}
onChange={setFieldValue}
onBlur={setFieldTouched}
error={errors.car}
touched={touched.car}
/>
</Form>
The props given to the render function are the route props listed in the documentation. What you want to do in this case is to pass down the props from the parent component, not the route props:
class ParentComponent extends React.Component {
render() {
const { props } = this;
const {
values,
touched,
errors,
setFieldValue,
setFieldTouched,
} = props;
return (
<Form>
<Switch>
<Redirect from="/" exact to="/form/location" />
<Route
path="/form/location"
render={() => <Pricing {...props} />}
/>
</Switch>
<MyRadio
value={values.car}
onChange={setFieldValue}
onBlur={setFieldTouched}
error={errors.car}
touched={touched.car}
/>
</Form>
);
}
}
And if you need both Formik's props and this component's you could do:
render={(formikProps) => <Pricing {...formikProps}, {...props} />}
That will create a long list of attributes from both props for Pricing to use.

Categories

Resources