Share data between component in react - reactjs

I have a component which is extending form like:
import React from "react";
import Form from "./common/form";
import AppFeature from "./common/appFeature";
class AddFeature extends Form {
render() {
<AppFeature role={"newRole"} />}
}
When I tried to get the role value in appfeature component through this.props.role. I'll get undefined.
Any workaround for this???

You're doSubmit function is not correct.
You need to update state - showFeatures to true to render AddFeature component.
You are calling history.push to a specific route which is not defined and uses React Router to do that.
Use below code and you will be able to get props to AddFeature component
doSubmit = async ex => {
try {
this.setState({
showFeatures: true
})
} catch (ex) {
console.log(ex.response);
}
};

Related

How to include the Match object into a Reacts component class?

I am using react router v5, and trying to get URL parameters by props match object into my react component class. However it is not working! What am I doing wrong here?
When I create my component as a JavaScript function it all works fine, but when I try to create my component as a JavaScript class it doesn't work.
Perhaps I am doing something wrong? How do I pass the Match object in to my class component and then use that to set my component's state?
here code:
import React, { Component } from 'react';
import { Link} from "react-router-dom";
export class JobDetail extends Component {
state = {
// jobsData: [],
}
async componentDidMount() {
const props = this.props.match;
console.log("---props data---",props); // it's showing undefined
}
render() {
return (
<>
test message
</>
)
}
}
export default JobDetail

How to render a component with props derivative from NextJS router

I'm trying to render a component that uses a dynamic router path prop. I want mysite.com/something to load the component with the something prop. If the route is mysite.com/somethingelse, I want to load the component with the somethingelse prop. Here's my code:
page.js:
import { useRouter } from "next/router";
import List from "./List";
function DefaultPage() {
const router = useRouter();
console.log(router.query.category); // Works correctly
return (
<div>
<List category={router.query.category} />
</div>
);
}
export default DefaultPage;
The component, list.js:
import React, { Component } from "react";
class List extends Component {
constructor(props) {
super(props);
console.log(this.props.category); // This is where I'm confused
}
static defaultProps = { category: "default" };
render() {
return <p>Hello</p>;
}
}
export default List;
The problem is, this.props.category always returns as default (my default prop), unless I recompile. It works perfectly after a fresh compile, but then breaks after every subsequent refresh in the browser.
I can visually see the router query returning the correct value in the log, but the component is rendering before everything else, thus returning a default value. Is there a way I can stop the List component from rendering before its own props are specified? Or is there a better way of doing this all together? Thanks.
I would do something like this in the DefaultPage component:
if(router.query.category === 'something') {
return <ListComponent/>
}
if(router.query.category === 'somethingElse') {
return <SomethingElseComponent/>
}
If you don't want to use two separate components, you could pass the prop to useEffect so it can re-render the component when that prop changes https://reactjs.org/docs/hooks-effect.html

React Hook error when loading Solid webId profile

I'm trying to use Solid's react-components to load a user's profile from their webId. I'm running into a problem with useLDflex(). There problem seems to be something to do with React Hooks, but I can't figure it out. My goal is to load the user's profile when the page loads; open to making whatever changes necessary. I'm using MobX for state.
Below is the code and below below is the error in the compiler/web browser. Thank you.
Code (React/JSX/TypeScript):
import React from 'react'; // 16.14.0
import { observer } from 'mobx-react';
import { observable } from 'mobx';
import { useLDflex } from '#solid/react'; // 1.10.0
#observer
export class Profile extends React.Component<{profileId: string}, {}> {
#observable webId = `https://${this.props.profileId}.solidcommunity.net/profile/card#me`;
#observable name = useLDflex(`[${this.webId}`)[0];
render() {
return (
<main role="Profile">
<div className="container">
webId: https://{this.props.profileId}.solidcommunity.net/profile/card#me
Name: {this.name}
</div>
</main>
)
}
}
Error:
src/components/profile/index.tsx
Line 9:24: React Hook "useLDflex" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
Search for the keywords to learn more about each error.
You cannot use React Hooks inside class component, ref here: https://reactjs.org/docs/hooks-faq.html#should-i-use-hooks-classes-or-a-mix-of-both
So you need to rewrite it to functional component with Mobx, or make a higher order component and pass the props into your class component (when your class is too complex to rewrite)
With FC:
import {observer} from "mobx-react";
const Profile = observer(({ profileId }) => {
// ...
const name = useLDflex(`...`);
// ...
})
HOC
const withName = (Component) => ({ profileId }) => {
const name = useLDflex('...');
return <Component name={name} profileId={profileId} />
}
export default withName(Profile);

Navigate to other page with props in React JS

I want to redirect from one page to other and pass props along with it. But i dont want these params in url.
Method :
saveForLater(){
if (typeof window !== "undefined") {
window.location.href = "./DataDisplay/";
}
};
I checked with urlparams we can set {"id":content} in url. But i do not wish to pass data in url.
I can not use Link / Route in the method . Is there any way to do it/any library to checkout? Pls suggest
CODE SAMPLE:
import React, { Component } from "react";
class DATAFETCH extends Component {
constructor(props) {
super(props);
this.state = {
Attachments: [],
validated: false,
isDoctor:false,
}
saveForLater(){
if (typeof window !== "undefined") {
window.location.href = "./DataDisplay/";
}
};
render() {
return (
/////// Various Fields
<Button
onClick={() => props.submit()}
>
)}
I think you've not quite understood how react works. Both Link and Route are components, so they can only be used & rendered within the render lifecycle function of a class-based component or return of a functional component. Outside of this the pattern to navigate to other routes is to use the history object to push to another route/path.
history.push('/DataDisplay');
If you need to send extraneous data along with the route push, you can use route state.
history.push({
pathname: '/DataDisplay',
state: {
// any values/objects/etc you want to also send to pushed route/path
},
});
Route state is accessed via the location object of route-props.
const { /* values/objects/etc */ } = props.location.state;
The route-props are only accessible via a component directly rendered by a Route, or by using the withRouter Higher Order Component or in the case of functional components using react hooks.
Your example code
import React, { Component } from "react";
import { withRouter } from 'react-router-dom'; // <-- import withRouter HOC
class DATAFETCH extends Component {
...
saveForLater(){
history.push({
pathname: '/DataDisplay',
state: {
id: content // <-- pass in content to key `id`
},
});
};
render() {
...
}
}
export default withRouter(DATAFETCH); // <-- decorate with withRouter HOC
To access on resultant route's component
props.location.state.id
Maybe you can use a store manager like the API Context.
Or one alternative like MobX or Redux.

I have to redirect the page based on location of the page. May i know which method is best practice

lifecycleMethodName (){ const presentPage = 'home/page1';if (this.props.location!==presentPage){this.pros.redirectTo(presentPage);}}
FYI. I have tried component will receive props and component did update but no luck. can some one help me ?
Use it in this way :-
import React, { useState } from 'react'
import { Redirect } from 'react-router-dom'
const Home = () => {
constructor(props){
this.state={
isRedirect : false,
presentPage : "home/page1"
}
}
const renderRedirect = () => {
if (this.state.isRedirect && this.props.location!==this.state.presentPage) {
return (
<Redirect to={{
pathname: '/home/page1'
}}
/>
);
}
}
const clicked = () => {
console.log('clicked');
this.setState({
isRedirect :true
})
}
return (
<div>
Home
{renderRedirect()}
<button onClick={() => clicked()}>click</button>
</div>
)
}
export default Home;
Or you want use lifeCycle method then call clicked() function in componentDidMount like below:-
componentDidMount(){
this.clicked()
}
This is a common use case. The React life cycle method you're looking for is componentDidMount.
componentDidMount (){ <<your code to redirect >>}
The above will trigger when the component is mounted. It will also work for server-side rendered components since the method only runs clientside.
However if your app is client-side only and your component is a Class component you can also run your code in the constructor itself, since it will have access to the props.
If you're in a function component, you can run it inside the component right away, there's no need to use any hook, since the function will have access to the props right away.

Resources