I'm relatively new to React and JavaScript and I'm building a website but I'm having a bit of an issue with passing Data via components from child to parent.
So:
I have my App.js script which is used as a router with react-router-dom, but I would like to store a boolean value using the useState hook. This boolean value that I would like stored should be passed on from a component called Login. I have the script setup to pass that data however the boolean is only stored as long as the Login COmponent page is active and when it is not rendered the boolean store by the useState hook in the App.js script just goes to 'undefined'. I'm assuming that this is happening because the app.js page constantly re-loads and re-renders, so how could I store that value even when the login page is not being rendered?
This is the code setup to pass that data:
app.js
const [authValue, setAuthValue] = useState(false);
const changeValue = (value) => {
setAuthValue(value)
}
And where the Login is called:
<Route path='/signin' element={<Login changeValue={changeValue}value={authValue} />} />
Login.jsx:
const Login = ({changeValue, value}) => {
const [isValid, setIsValid] = useState(true)
changeValue(isValid)
}
The useState hook in React is a solution for component-level state management in functional components.
So, the value of isValid is stored only in Login.js and can be passed as a props to its children components.
Of course, you can also pass some state (or values) from child to parent via functions passed from parent into the child, but this is not the way you should consider if you want to use a state in whole app.
If you need to have the state that should be persistent across the app components, even after one component was unmounted, you should consider global management solutions like React Context API, Redux, MobX or similar libraries.
Try putting the changeValue(isValid) into a useEffect() hook. So:
useEffect(() => {
changeValue(isValid)
}
Related
I have the following component where within the useEffect, I am calling some data reading related
functions meant to happen once on load.
The problem is, some of the prop data are not available at this stage (still undefined) like the prodData and index.
They are only available when I get into the Nested components like <NestedComponent1 />.
I wish to move this logic into the nested components which will resolve this issue.
But I do not want to repeat these code inside the useEffect for each component. Instead looking to write these 7 lines once maybe in a function
and just call it with the 3 NestedComponents.
Issue is that there is a higher order function wrapping here plus all the values like prodData and index is coming from Redux store.
I can't just move all these logic inside useEffect into a normal JS function and instead need a functional component for this.
And if I make a functional component to perform these operations, I can't call it in the useEffect for each of the NestedComponents.
Cos this is not valid syntax.
React.useEffect(() => {
<NewlyCreatedComponentWithReadingFunctionality />
}, []);
Thus my query is, is there a way I could write a functional component which has the data reading logic inside its useEffect.
And then extend this functional component for each of the functional components so that the useEffect would just fire
when each of these NestedComponents are called?
Doesn't seem to be possible to do this thus looking for alternatives.
This is the existing component where some of these prop values are undefined at this stage.
const MyComponent = ({
prodData,
index,
country,
highOrder: {
AHigherOrderComponent,
},
}) => {
// this is the logic which I am looking to write once and be
// repeatable for all the NestedComponent{1,2,3}s below.
React.useEffect(() => {
const [, code] = country.split('-');
const sampleData = prodData[index].sampleData = sampleData;
const period = prodData[index].period = period;
const indication = prodData[index].indication = indication;
AHigherOrderComponent(someReadDataFunction(code, sampleData));
AHigherOrderComponent(someReadDataFunction(code, period);
AHigherOrderComponent(someReadDataFunction(code, indication);
}, []);
return (
{/* other logics not relevant */}
<div>
<div>
<NestedComponent1 />
<NestedComponent2 />
<NestedComponent3 />
</div>
</div>
);
};
export default connect( // redux connect
({
country,
prodData,
index,
}) => ({
country,
prodData,
index,
})
)(withHighOrder(MyComponent));
React components implement a pattern called composition. There are a few ways to share state between parts of your React application but whenever you have to remember some global state and offer some shared functionality, I would try and manage that logic inside a context provider.
I would try the following:
Wrap all your mentioned components inside a context provider component
Offer the someReadDataFunction as a callback function as part of the context
Within your provider, manage react state, e.g. functionHasBeenCalled that remembers if someReadDataFunction has been called already
Set functionHasBeenCalled to true inside someReadDataFunction
Call someReadDataFunction inside your components within a useEffect based on the props data
This way, your application globally remembers if the function has been executed already but you can still use the latest data within your useEffect within your components to call someReadDataFunction.
I am practising React props by building an input form using hooks. The idea is when I enter the inputs in NewList component and click the submit button, its values will render on the MyJobList component in a form of HTML elements. The issue is when I submitted the form, nothing is displaying on the web page. It could be that I am passing the data incorrectly.
Here are my codes. I have minimized it to highlight possible problems and included a link to full codes down below:
newlist.js
const NewList = () => {
const [inputState, setInputState] = useState({});
const onSubmitList = () => {
setInputState({
positionTitle: `${inputs.positionTitle}`,
companyName: `${inputs.companyName}`,
jobLink: `${inputs.jobLink}`
});
};
const { inputs, handleInputChange, handleSubmit } = CustomForm(onSubmitList);
myjoblist.js
const MyJobList = inputs => (
<div>
<h3>{inputs.positionTitle}</h3>
<p>{inputs.companyName}</p>
<p>{inputs.jobLink}</p>
</div>
);
navbar.js
const Navbar = inputState => (
<Router>
<Switch>
<Route path="/my-list">
<MyJobList inputs={inputState} />
</Route>
</Switch>
</Router>
);
Any help and guidance are much appreciated.
Here's a link to complete code: Code Sandbox
So, you need the persisting state to live in a shared parent component, in the existing components, your choices would be either App.js or navbar.js (side note, you should PascalCase your component file names, so NavBar.js). Ideally, you should make a shared container that will hold the state. When you navigate away from the newlist component to view myjoblist, the newlist component unmounts and you lose the state. With a shared parent component, the parent won't unmount when it renders its children (newlist & myjoblist).
Another problem is that you you are passing a callback to your custom hook, but the callback doesn't have any arguments. In your handle click, you need to pass it the inputs. You also cannot set your state to an empty string before you pass the inputs to your callback, do it after.
const handleSubmit = event => {
e.preventDefault()
callback(inputs)
setInputs({}) // set it back to the default state, not a string
}
Lastly, the inputState in navbar is an undefined variable. You are rendering Navbar inside your app and not passing it any props. The first argument to a functional component in react is props. So, even if you were passing it state, you'd need to extract via props.inputState or with destructuring.
Here's a working example that could still use some clean up:
https://codesandbox.io/s/inputform-with-hooks-wwx2i
I'm new in react hooks and I just don't see this on docs:
const MyComponent = ({myProp}) => {
const [myPropHook, setPropHook] = useState(myProp)
...
}
I'm wondering if this is a good practice?
The value you pass to useState is used as a starting value for the state variable. So, when your component props change, they will not affect the state variable you are using. The initial value would be the first props sent to the component and after that can be modified only using the setPropHook function.
So, in short, it is definitely a code smell to use props as initializers for useState because reading the code does not correctly convey what will actually happen.
You don't see it much because it doesn't make a lot of sense in terms of how a React app should distribute its state.
If a prop value is set higher up the tree, it shouldn't be used as part of the separate state within a component. It makes sense to use prop values to determine the state of a component indirectly as in 'if the prop is this, then set the state to that', but not to directly copy the prop in to the initial value.
In other words, the internal state of a component (accessed via the useState and useReducer Hooks) should be determined by the component, not directly by the parent(s).
Yes, this is bad. What you're doing is passing a prop to the state, and it is discouraged by many.
The React docs says that "using props to generate state often leads to duplication of “source of truth”, i.e. where the real data is.". The danger is that if the props is changed without the component being refreshed, the new prop value will never be displayed, because the initialization of state from props only runs when the component is first created.
The only exception would be to use the prop as a seed for an internally-controlled state. After several years of react development, I've never encountered such a case.
Further reading:
React component initialize state from props (SO question)
React Anti-Patterns: Props in Initial State (medium.com article)
Why Setting Props as State in React.js is Blasphemy (blog post)
If you are trying to receive a prop to that functional component, then yes, but not exactly like you have it written. So in the parent component you will have something like this:
const App = () => {
const [resource, setResource] = useState("posts");
and then there is a component inside the JSX like so:
const App = () => {
const [resource, setResource] = useState("posts");
return (
<div>
<div>
<button onClick={() => setResource("posts")}>Posts</button>
<button onClick={() => setResource("todos")}>Todos</button>
</div>
<ResourceList resource={resource} />
</div>
);
};
That ResourceList component has to be able to receive the props that the App component is passing to it. Inside a class-based component you would do {this.props.resource}, but in our case, where its a functional component using React hooks you want to write it like so:
const ResourceList = (props) => {
const [resources, setResources] = useState([]);
or via ES6 destructuring like so:
const ResourceList = ({ resource }) => {
const [resources, setResources] = useState([]);
I have a route which takes an id and renders the same component for every id, for example :
<Route path='/:code' component={Card}/>
Now the in the Link tag I pass in an id to the component.Now the Card component fetches additional detail based on the id passed. But the problem is it renders only for one id and is not updating if I click back and goto the next id. I searched and found out that componentsWillReceiveProps can be used but during recent versions of React it has been deprecated. So how to do this?
Putting current location as key on component solves problem.
<Route path='/:code' component={(props) => <Card {...props} key={window.location.pathname}/>}/>
I just ran into a similar problem. I think you are conflating updating/rerendering and remounting. This diagram on the react lifecycle methods helped me when I was dealing with it.
If your problem is like mine you have a component like
class Card extend Component {
componentDidMount() {
// call fetch function which probably updates your redux store
}
render () {
return // JSX or child component with {...this.props} used,
// some of which are taken from the store through mapStateToProps
}
}
The first time you hit a url that mounts this component everything works right and then, when you visit another route that uses the same component, nothing changes. That's because the component isn't being remounted, it's just being updated because some props changed, at least this.props.match.params is changing.
But componentDidMount() is not called when the component updates (see link above). So you will not fetch the new data and update your redux store. You should add a componentDidUpdate() function. That way you can call your fetching functions again when the props change, not just when the component is originally mounted.
componentDidUpdate(prevProps) {
if (this.match.params.id !== prevProps.match.params.id) {
// call the fetch function again
}
}
Check the react documentation out for more details.
I actually figured out another way to do this.
We'll start with your example code: <Route path='/:code' component={Card}/>
What you want to do is have <Card> be a wrapper component, functional preferrably (it won't actually need any state I don't think) and render the component that you want to have rendered by passing down your props with {...props}, so that it gets the Router properties, but importantly give it a key prop that will force it to re-render from scratch
So for example, I have something that looks like this:
<Route exact={false} path="/:customerid/:courierid/:serviceid" component={Prices} />
And I wanted my component to rerender when the URL changes, but ONLY when customerid or serviceid change. So I made Prices into a functional component like this:
function Prices (props) {
const matchParams = props.match.params;
const k = `${matchParams.customerid}-${matchParams.serviceid}`;
console.log('render key (functional):');
console.log(k);
return (
<RealPrices {...props} key={k} />
)
}
Notice that my key only takes customerid and serviceid into account - it will rerender when those two change, but it won't re-render when courierid changes (just add that into the key if you want it to). And my RealPrices component gets the benefit of still having all the route props passed down, like history, location, match etc.
If you are looking for a solution using hooks.
If you are fetching data from some API then you can wrap that call inside a useEffect block and pass history.location.pathname as a parameter to useEffect.
Code:
import { useHistory } from "react-router";
const App = () => {
const history = useHistory();
useEffect(() => {
//your api call here
}, [history.location.pathname]);
};
useHistory hook from react-router will give the path name so the useEffect will be called everytime it (url) is changed
as described by #theshubhagrwl but
you can use location.href instead of location.pathname to work in all condition
import { useHistory } from "react-router";
const App = () => {
const history = useHistory();
useEffect(() => {
// do you task here
}, [history.location.href]);
};
You can use use UseLocation() from "react-router-dom"
and then use that object in useEffect dependency array.
import {useLocation} from "react-router-dom";
export default function Card() {
const location = useLocation();
useEffect(()=>{}, [location]);
return(
// your code here
);
}
In React Router v4 Adding a Switch tag after Router fixes the problem
I'm making a react application that shows details about the pokemon you searched. So I have a Home component which has an input field + submit button.
I want to render my api call in my Main component.
The question that I have is : How can I pass the value from this input field that is located in my home component to my main component when I enter submit?
home component details
I need this value to update my pokemon name state in my Main component in order to get the pokemon name for my fetch call.
I need this value to be stored inside my 'searchValue' state.
Main component details
any tips?
One of the ways you can achieve this by Using ref in reactjs , Inside your Main Component you need to make a reference, like :
componentDidMount() {
this.props.onRef(this);
}
// Delete the reference once component is unmounted
componentWillUnmount() {
this.props.onRef(undefined);
}
And then create a method , which will receive the values from a the Home component and then setState like :
method(values) {
this.setState({ searchValue: values });
}
Now inside your Home component you need to reference method component before your input like , (You can amend it accordignly)
import Home from './Home'
<Home onRef={ref => (this.home = ref)} />
<Form onSubmit={e => { this.onSubmit(e) }}
Make sure to add onSubmit method inside main component which will send the values to Home Component
onSubmit = values => {
this.home.method(values);
}
You can read more about Ref and the DOM on React Documentation
I would propose you to take a look at redux which is great tool for state management. Redux will ensure you have a single source of truth.
What you will have to do is create an Action which would dispatch an event to update the state, a Reducer which would update the state (value of the search-key in redux-store). Your Main component will read the data from the API (Same Action-Reducer way) & render it without having to bother about the current state. I can explain the whole architecture in detail if you are more interested. This architecture will have less bugs & clear flow of information including shared state between components.
I know this sounds bit too complex but its worth a try if your application is growing.
Few suggestions:
Your Main component has too much of logic. Components should have least logic as possible so they are more deterministic. Please also read about React Stateless functional components
Here are some links if you wish to take redux path
10-tips-for-better-redux-architecture
Redux Best Practices