how to pass state values as props to child component - javascript

I am trying to pass some constant values which is stored in state of parent component to child component and would like to pass down in tree.
is it right to store the constant values in state of App.tsx or any other suggestion
how can i access for example GrTag or sTag from App.tsx to Subchild component.
App.tsx
class App extends Component {
constructor(props) {
super(props);
this.state = {
sTag : "00D",
pTag : "010",
adTag : "020",
dbTag : "030",
GrTag : "040",
serTag : "00E",
modTag : "060",
iTag: "018"
};
}
render() {
return(
<div >
<Child {...this.state}/> //is this right way to pass
</div>
);
}
}
Child.tsx
class Child extends Component {
constructor(props) {
super(props);
}
render(){
return(
<div>
{
<Subchild /> //want to pass the state values from App.tsx
}
</div>
);
};
}
Subchild.tsx
class Subchild extends Component {
constructor(props) {
super(props);
}
render(){
return(
<div>
{
// want to print sTag value here
}
</div>
);
};
}

The way you are spreading the state {...this.state} will pass all the state values as props to the child components . If you need all the state values in your Child component as props then what you are doing is fine .
But if you just need the stag from the App inside the subChild then you can do
<Child {...this.state}/>
In your Child.tsx
<Subchild {...this.props} />

To solve your problem, pass the props from the child to the sub child. Like this;
class Child extends Component {
constructor(props) {
super(props);
}
render(){
return(
<div>
{
<Subchild {...this.props}/> //want to pass the state values from App.tsx
}
</div>
);
};
}
But mind you. This is not a good way to pass data to components.
If you have data that can be shared amongst many components in your app, consider using REACT REDUX or MOBX. I personally recommmend using Redux.

App.tsx
class App extends Component {
constructor(props) {
super(props);
this.state = {
sTag : "00D",
pTag : "010",
adTag : "020",
dbTag : "030",
GrTag : "040",
serTag : "00E",
modTag : "060",
iTag: "018"
};
}
render() {
return(
const data = this.state;
<div >
<Child dataToClid = {data}/> //is this right way to pass
</div>
);
}
}
Child.tsx
class Child extends Component {
constructor(props) {
super(props);
this.state = {
data: this.props.dataToClid
}
}
render(){
const data = this.state;
return(
<div>
{
<Subchild dataToSubClid = {data}/> //want to pass the state values from App.tsx
}
</div>
);
};
}
SubChild.tsx
class Subchild extends Component {
constructor(props) {
super(props);
this.state = {
data: this.props.dataToSubClid
}
}
render(){
const {GrTag, sTag} = this.state;
return(
<div>
<p>{GrTag}</p>
<p>{sTag}</p>
</div>
);
};
}
you can do this way or you can use Context API for pass data from parent to child

Related

Passing state from child class to parent

I know that this is probably the most asked question about React, but none of the answers helped me.
I have 2 classes:
Child
class Preview extends Component {
constructor(...args) {
super(...args);
this.state = {
isCommentOpen: false
};
this.handleComment = ::this.handleComment;
render() {
return(
button type="button" onClick={this.handleComment}>Comment</button>
)}
handleComment(){
this.setState({isCommentOpen: !this.state.isCommentOpen});
}
export default Preview;
Parent
class Profile extends Component {
render(){
return(
<div>
<_.Preview />
//the place where I want to add validation from the component above
{this.state.isCommentOpen ? <span>Cool</span> : null}
</div>
}
You should not mutate or directly assign this.props as shown in the other answer:
this.props.isCommentOpen = !this.props.isCommentOpen // <-- DON'T DO THIS! 🎃
Instead, you should have a callback function to let the Parent component update the child component:
class Profile extends Component {
constructor(props) {
super(props);
this.state = {
isCommentOpen: false;
}
this.handleComment = this.handleComment.bind(this); // <-- important!
}
handleComment() {
this.setState({ isCommentOpen: !this.state.isCommentOpen });
}
render() {
return (
<div>
<Preview handleComment={this.handleComment} />
{ this.state.isCommentOpen ? <span>Cool</span> : null }
</div>
)
}
}
export default Profile
The child component then only needs to call this.props.handleComment:
// Child Component:
class Preview extends Component {
render() {
return(
<button type="button" onClick={this.props.handleComment}>Comment</button>
}
}
export default Preview;

How to pass state property to child component in constructor with React.js?

How to pass a state property of the father component as props for the child component in the constructor? I have something like this:
class FatherComponent extends Component {
constructor(props) {
super(props);
this.state = {
status: true
components: [
{ component: (
<ChildComponent
statusAsProps={this.state.status} />
)
}
]
};
}
render(){
return(
<div>{this.state.components[0].component}</div>
)
}
But shows me the error of this.state is undefined.
Is a way to bind "this" of the state as a prop for the children component?
You're using this.state inside itself before it is even defined and assigned a value. That's why the undefined. Avoid complexity and simply render the child component by passing in the required props from the parent's state.
class FatherComponent extends Component {
constructor(props) {
super(props);
this.state = {
status: true
};
}
render() {
return (
<div>
<ChildComponent statusAsProps={this.state.status} />
</div>
)
}
}
It is not a good idea to store components on the state. You can just define that in your render
class FatherComponent extends Component {
constructor(props) {
super(props);
this.state = {
status: true
};
}
render(){
return(
<div>
{ <ChildComponent statusAsProps={this.state.status} }
</div>
)
}
method

Reactjs : How to change props data from parent component that already distribute to child component?

I just creating a project and use a several component for a page and pass data by using props to each components. The problem is, when I have already change data from parent component to child component by using props and I have update the data from parent component, the child component still using the old data.
The example is just like this:
class Child extends Component{
constructor(props){
super(props);
this.state = {
variabel : props.variable
}
}
render() {
return (
<div>
<h1>{this.state.variable}</h1>
</div>
)
}
}
class Parent extends Component{
constructor(props){
super(props);
this.state = {
variabel : 'Hello'
}
}
render() {
return (
<div>
<Child variable={this.state.variable} />
</div>
)
}
}
So, when I run the page and update the variabel state in Parent Component, Child Component still show the old value. How to make it updated as the Parent Component data? Or I must using Redux for this case?
In general you'll only want to keep one particular piece of state in one place. If you reassign it in the constructor of Child, it will not update when the parent's state updates. So something like this pattern should work:
class Child extends Component{
// Note that no constructor is needed as you are not initializing any state or binding any methods.
render() {
return (
<div>
<h1>{this.props.variable}</h1>
</div>
)
}
}
class Parent extends Component{
constructor(props){
super(props);
this.state = {
variable : 'Hello'
}
}
render() {
return (
<div>
<Child variable={this.state.variable} />
</div>
)
}
}
A warning note about not initializing state with props is in the React docs for constructor, as a matter of fact.
Mitch Lillie's answer is the correct one. You should have only one source of truth.
In general, it's a good idea to keep the state in the nearest common ancestor of the components that depend on the state. Then you pass the props down.
If, however, you need to keep a copy of the prop in the child state, you should use the life cycles that React provides.
Codepen Live Demo
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
variable: props.variable,
};
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (this.props.variable !== prevState.variable) {
this.setState({
variable: this.props.variable,
});
}
}
render() {
const varState = this.state.variable;
const varProps = this.props.variable;
return (
<div>
Child props: {varProps}
<br />
Child state: {varState}
</div>
);
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
setInterval(this.updateTime, 1000); // refresh every second
this.state = {
variable: new Date().toLocaleString(),
};
}
updateTime = () => {
this.setState({
variable: new Date().toLocaleString(),
});
}
render() {
const time = this.state.variable;
return (
<div>
<div>
Parent: {time}
</div>
<Child variable={time} />
</div>
);
}
}
ReactDOM.render(
<Parent />,
document.getElementById('container')
);

ReactJS calling functions from child component [duplicate]

I have a parent and child compoents and I want to call a parent method in the child component like this:
import Parent from './parent.js';
class Child extends React.Component {
constructor(props) {
super(props);
};
click() {
Parent.someMethod();
}
render() {
<div>Hello Child onClick={this.click}</>
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
};
someMethod() {
console.log('bar');
}
render() {
<div>Hello Parent</>
}
}
This returns an error message:
Uncaught TypeError: _Parent2.default.someMethod is not a function
How can this parent method be called in the child component?
Try this. Passing the function down as props to the child component.
import Parent from './parent.js';
class Child extends React.Component {
constructor(props) {
super(props);
};
click = () => {
this.props.parentMethod();
}
render() {
<div onClick={this.click}>Hello Child</div>
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
};
someMethod() {
console.log('bar');
}
render() {
<Child parentMethod={this.someMethod}>Hello Parent, {this.props.children}</Child>
}
}
You can try doing something like calling the function of parent by passing the state of your parent to the child and then call using the props in child class.
class FlatListItem extends Component{
constructor(props){
super(props)
}
render(){
return(
<TouchableOpacity style={styles.button}
onPress=
{(item)=>this.props.parentFlatlist.delete(item)}></TouchableOpacity>
</Swipeout>
)
}}
And now consider you have a parent class RandomList:
class RandomList extends Component{
static navigationOptions = ({navigation}) =>{
return{
headerTitle: 'Random List'
}
};
state = {
lists : [],
refreshing : false
}
constructor(props){
super(props)
}
delete= (item) =>{
//delete your item
console.log(item)
}
render(){
return(
<BackgroundImageComponent>
<FlatList
keyExtractor={item => item}
data = {this.state.lists}
renderItem = {({item,index}) => (
<FlatListItem onPress={()=>this.seeTheList(item)} item1={item} parentFlatList={this} index={index}>
</FlatListItem>
)}
/>
</ScrollView>
</BackgroundImageComponent>
)
}}export default RandomList
See here, I am passing parentFlatlist={this} and then would be using the same instance later in the child class.
The main idea is to focus upon the way I am able to render the delete function and not to focus upon the code. Forgive me if the code is misplaced or broken.

Can I modify a parent state of a component in ReactJs?

Let's say I'm having the following component:
class LeftPanel extends React.Component {
constructor(props) {
super(props);
this.state = {abc: 'xyz'};
}
render() {
return (
<div>
<Thumb src={img1}/>
<Thumb src={img2}/>
</div>);
}
Inside the component, there's an inner component called Thumb that goes like there:
class Thumb extends React.Component {
constructor(props) {
super(props);
this.state = { src: props.src };
}
render() {
return (
<div>
<img src={this.state.src}></img>
</div>
);
}
}
Question: Can I modify the state of LeftPanel Component inside Thumb? If yes, how?
create a method in Left panel to handle the event. Then pass the method to the child component.
Now if you want to pass data to the parent I would recommend a library like flux or redux. since redux has a global state it is accessible to all components. When you modify the global state to whole application is rerendered with the new state. The new state is visible by all components.
class LeftPanel extends React.Component {
constructor(props) {
super(props);
this.modifyLeftpanel = this.modifyLeftpanel.bind(this);
this.state = {abc: 'xyz'};
}
modifyLeftpanel(newvar){
//Do something with newvar
}
render() {
return (
<div>
<Thumb src={img1} modifyLeftPanel={this.modifyLeftpanel} />
<Thumb src={img2} modifyLeftPanel={this.modifyLeftpanel} />
</div>);
}
here is the thumb
class Thumb extends React.Component {
constructor(props) {
super(props);
this.state = { src: props.src };
this.doSomething = this.doSomething.bind(this);
}
doSomething(){
this.props.modifyLeftpanel(10);
}
render() {
return (
<div>
<img src={this.state.src}></img>
<button onClick={this.doSomething}>Modify Parent</button>
</div>
);
}

Categories

Resources