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
Related
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"
I want to know I have one parent component and two child components and these child components are separated according to the user role. I have passed the parent state in these child components. In the beginning, both child components have the same state value, but if I update the state value in one child component, it will not update the state value in another component why.
Here is an example code.
import React, { useEffect, useState } from "react";
import Demo1 from "./Demo1";
import Demo2 from "./Demo2";
const Demo = () => {
const [staVal, setStaVal] = useState("hi");
console.log(staVal);
const user = JSON.parse(localStorage.getItem("auth"));
return (
<div>
{user.role === "user" ? (
<Demo1 staVal={staVal} handler={() => setStaVal("google")} />
) : (
<Demo2 staVal={staVal} />
)}
</div>
);
};
export default Demo;
Demo1 component:
import React from "react";
const Demo1 = ({ staVal, setStaVal, handler }) => {
return (
<>
<div>demo1:{staVal}</div>
<button onClick={handler}>clik</button>
</>
);
};
export default Demo1;
Demo 2 component:
import React from "react";
const Demo2 = ({ staVal }) => {
return <div>demo2:{staVal}</div>;
};
export default Demo2;
Accessing localStorage is a side effect.
Side effects cannot be called from the render method (for Class components) or the top level (function components).
In your code, access the localStorage inside useEffect(()=>{}, []) or
inside componentDidMount if you want to make it a class component.
use the useEffect to get the item from the local storage.
const [user,setUser]=useState(null);
useEffect(()=>{
const currentUser = JSON.parse(localStorage.getItem("auth"));
setUser(currentUser)
},[])
return (
<div>
{user.role === "user" ? (
<Demo1 staVal={staVal} handler={() => setStaVal("google")} />
) : (
<Demo2 staVal={staVal} />
)}
</div>
);
};
Hi developers I'm just a beginner in React.js. I tried to print props by passing from parent to child.
This is app.js file
import React from "react";
import Hooks from "./components/ReactHooks1";
import Hooks2 from "./components/ReactHooks2";
const App = () => {
return (
<div>
<h1>
Welcome to React App
</h1>
<Hooks2 title2={"Welcome"}/>
</div>
)
}
export default App
This is child component file
import React from 'react';
const Hooks2 = (props) => {
console.log(props);
}
export default Hooks2;
I just try to print props but it shows an empty object. what am I doing wrong please help me on this
You should return something or null to parent component from child, when you're using it in parent component. This will solve your problem
export const Hooks2 = (props) => {
console.log(props);
return <></>;
}
#Rasith
Not sure why would you want to do this, but if you're trying to pass a child component that would print something to the console. In this case you need to destructure the component's props. Here's an article about it from MDN.
This is how I would do it:
const CustomComponent = ({title}) => {
console.log(title)
}
const App = () => {
return (
<>
<h1>Hello World</h1>
<CustomComponent title={"Welcome"}/>
</>
);
};
For the title to be printed to the console, no need to add a return statement to the child component. Again, not sure why you would do this, but there you go.
Well trying to console.log title certainly would not work because what you are passing is called title2. Also your child component is not returning anything.
First, you have to return anything from your child component( even a fragment )
You can access title2 in the child component with any of these methods:
1- using props object itself
const Hooks2 = (props) => {
console.log(props.title2);
return;
}
2- you can also destructure props in place to access title2 directly
const Hooks2 = ({title2}) => {
console.log(title2);
return ;
}
You have to use destructuring in your ChildComponent, to grab your props directly by name:
const Hooks2 = ({title2}) => {
console.log(title2);
}
You can read a little bit more about it in here: https://www.amitmerchant.com/always-destructure-your-component-props-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!");
}
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