Reputation: 527
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.
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>
);
};
}
Upvotes: 0
Views: 2096
Reputation: 188
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
Upvotes: 1
Reputation: 5497
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} />
Upvotes: 2
Reputation: 120
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.
Upvotes: 1