How to send data from one react component to another react component? - javascript

Here I get some data from the 'Order' component and then I want to send this data to Navigate but all I get when using 'props.order_data' in 'Navigate' is undefined. How can I use this data in 'Navigate'?
function App(){
function getData(some){
console.log(some);
return(<Navigate order_data= {some}/>);
}
return(
<div>
<Navigate />
<Service/>
<Order onAdd={getData}/>
<Review />
<Foot />
</div>
);
}
export default App;

You need to use useState hook to maintain a state. Since you have your Navigate and Order component in the same Parent App.
Do like this
import { useState } from "react";
function App(){
const [some, setSome] = useState(null); // Initial some value is null
function getData(data){
setSome(data); // This will update some state value
}
return(
<div>
<Navigate order_data={some}/>
<Service/>
<Order onAdd={getData}/>
<Review />
<Foot />
</div>
);
}
export default App;

What you are trying to do won't work as the return-value of the getData function is passed to the Order-component's onAdd function.
I would suggest that you create a state for the order_data in your App-component and pass the state as a prop to the Navigate-element that you are returning. You will need to update the state as soon as you retrieve the data (e.g. in getData function).
React will take care of updating the component as soon as the state changes.
See React documentation for more details:
https://reactjs.org/docs/lifting-state-up.html

Related

how do i pass a the input value of the textfield from some component to another component in reactjs?

I am trying to pass the value of the text area from some component in reactjs to be used in another react component. the component value is stored in the first component in a useState hook so I want to access it in another component and run map() function around it . Is this possible in reactjs ? I don't want to put the whole thing in app.js because that is just plain HTML which I don't want. I want to use reactjs function components instead ?
first component:
import React, { useState, useRef, useEffect } from "react";
function Firstcomp() {
const [quotes, setQuotes] = useState(["hi there", "greetings"]);
const reference = useRef();
function sub(event) {
event.preventDefault();
setQuotes((old) => [reference.current.value, ...old]);
console.log(quotes);
return;
}
return (
<>
<div>
<div>
<div>
<h4>jon snow</h4>
</div>
<form onSubmit={sub}>
<textarea
type="textarea"
ref={reference}
placeholder="Type your tweet..."
/>
<button type="submit">Tweet</button>
</form>
{quotes.map((item) => (
<li key={item}>{item}</li>
))}
{/* we can use card display taking item as prop where it
will do the job of filling the <p> in card entry */}
</div>
</div>
</>
);
}
export default Firstcomp;
second component
import React from "react";
function SecondComp(props) {
return (
<div>
<p>{props.message}</p>
</div>
);
}
export default Secondcomp;
Use a global management state like Recoil, Redux ot Context
import React from 'react';
export const UserContext = React.createContext();
export default function App() {
return (
<UserContext.Provider value="Reed">
<User />
</UserContext.Provider>
)
}
function User() {
const value = React.useContext(UserContext);
return <h1>{value}</h1>;
}
on the exemple above we used useContext hook to provide a global variable "value", even its not declared directly in User component, but you can use it by calling the useContext hook.
in this exemple the return value in the user component is "Reed"

Why onClick event doesn't change the props.title in React

I wanna change the title by clicking the button but it doesn't change, can I have an explanation why is that happens?
import './ExpenseItem.css';
import ExpenseDate from './ExpenseDate';
import Card from './Card';
function ExpenseItem(props){
let title = props.expenseTitle;
function clickedFunc(){
title = "Update!";
}
return(
<Card className='expense-item'>
<ExpenseDate expenseDate={props.expenseDate}></ExpenseDate>
<div className='expense-item__description'>
<h2>{title}</h2>
<div className='expense-item__price'>
₹{props.expenseAmount}
</div>
</div>
<button onClick={clickedFunc}>Click</button>
</Card>
);
}
export default ExpenseItem;
This is not how data is handled with React.
The title should be stored in a state variable (see useState).
Once the data is stored in a state variable, you will have to set it with setState. When setState is called in React, the component holding the state variable re-renders. This will in turn cause your ExpenseItem component to re-render because it is a child component of whatever higher level component passed it props.
In your parent component, you should see something like:
require { useState } from 'react';
const ParentComponent = (props) => {
const [title, setTitle] = useState('Original Title');
...
...
...
return (
<div className="ParentComponent">
<ExpenseItem
title={title}
setTitle={setTitle}
expenseAmount={expenseAmount}
/>
</div>
)
}
Then, in your clickedFunc() function:
function clickedFunc() {
props.setTitle("Update!");
}

Can I update the state of a prop

Im new to React. Can we change the state of a prop? For eg I have 2 pieces of code
App.js
import React, { useState } from 'react'
import Print from '../components/Print/print'
const [text, setText] = useState("Hi");
<Print text = {text} />
print.js
import React, { useState } from 'react'
const Print = (props) => {
return(
<p>props</p>
)
export default Print
Is there a way to change the state of the prop i.e use useState() in print.js to update the state. For eg can we do something like setText(prop) in print.js. If not like this then how would you trigger a state change from print.js for variable tech in App.js ?
You cannot and shouldn't try to change the state or values of the props directly in the child component. For changing props you can pass the function as a prop and then emit the new value to that function. So the function will change your props into the parent component and it will further pass down to its child.
<Print text = {text} changeText = {(newVal) => setText(newVal)}/>
And in your child component call this changeText function with new value.
return (
<>
<p>{props.text}</p>
<div onClick={props.changeText('Hello')}>Change Text</div>
</>
);
FYI, {props} is an array and you can access text by {props.text}
you can try this
Pass text and setText in print.js through props
then use setText to update the state of the components

Is there a way to export setState outside stateless components in react?

Consider this example
export function InsideHoc(props){
const [A, setA] = useState(false);
return({if(A) && (<h1>Print something</h1>)});
}
In another file
import {A, setA} from './inside-file';
function ToggleFromOutside(){
return(<p onClick={setA(!A)}>Verify</p>);
}
Can setA be exposed outside so that the state of this component be changed from outside? I know this can be done through redux. But without using this, is there a way to change the state of one component?
Structure is like this
import {withCreateHOC} from './external';
import childComponent from './child';
class A extends React.Component {
render(){
<Another menus={(item) => <MenuItems object={item} />}
/>
}
}
export default withCreateHOC(A, {custom: childComponent, title: 'Add'});
//withCreateHOC renders modal here as well as it has a button to toggle the state. Same state should be used from below function
function MenuItems(){
return(<button onClick={displayModal}>)
}
Yes.
You can lift the state in that case. This works good if you don't need to pass down the setState to far down the tree.
If you don't want to pass the setState function all the way down the React element tree, you will need to use context, redux or some other state handling.
Example state lift
export function Parent(){
const [message, setMessage] = useState("Hello World");
return (
<>
<Child1 message={message} />
<Child2 changeMessage={setMessage} />
</>
);
}
// Can be in other file
function Child1(props){
return(<p>{props.message}</p>);
}
// Can be in other file
function Child2(props){
return(
<a onClick={() => props.changeMessage("Changed")}>
I can change things in other components.
</a>
);
}
Example of React tree with shared context/redux
<WithRedux>
<App>
<Navigation />
<Modal />
<PageRenderer />
<SomeList>
<ListItem />
<ListItem />
</Somelist>
</App>
<WithRedux>
All the children of the WithRedux component can access the state and modify it.
(PS: You can wrap the App with the HOC withRedux etc, this example is just for visualization)

Passing props to a React Redux connected component wrapped in HOC

I am using a HOC to wrap all my components with the Redux Provider. But when using the components individually I sometimes need to pass props to them and using ownProps gives me the props from the HOC wrapper.
How can I pass props directly to the connected component?
I am essentially sprinkling React to an existing site, so I need to render my components to the DOM using HTML elements as containers. I want all the containers to be connected to the store but I also want to pass data directly to the HTML elements on the page and use that data in the component.
// HOC component 'withStore.js'
export default function (WrappedComponent) {
function ReduxStore() {
return (
<Provider store={ store }>
<WrappedComponent testProp="Dont show me!" />
</Provider>
);
}
return ReduxStore;
}
// The connected component I want to pass props directly to
export class ListingThumbnails extends PureComponent {
render() {
const {
ownProps,
} = this.props;
console.log(this.props.ownProps);
}
}
const mapStateToProps = (state, ownProps) => ({
state,
ownProps,
});
export default withStore(connect(mapStateToProps)(ListingThumbnails));
// Rendering to the DOM
ReactDOM.render(
<ListingThumbnailsComponent testProp="Show me!" />,
document.querySelector('#listing-thumbnails-container'),
);
The console log is displaying the props passed to the WrappedComponent
But I want it to show the props passed to the ListingThumbnailsComponent
I'm not sure to get your problem, but your ReduxStore is a component now. It's a component around your "wrapped component". It means that you have to pass the props of the ReduxStore to its child to console log the props at a deeper level:
export default function (WrappedComponent) {
function ReduxStore(props) {
return (
<Provider store={ store }>
<WrappedComponent {...props} />
</Provider>
);
}
return ReduxStore;
}

Categories