Reputation: 99
I have an array that I want to pass to a grandchild component.
class App extends Component {
constructor(props) {
super(props);
...
}
componentDidMount() {
array = ['a', 'b', 'c'];
}
render() {
return (
<Child arrayData={this.props.arrayData} /> ???
)}
I know that I have to pass the data to the child first (and then to the grandchild from there) via a prop but how do I format it? And how does the child receive the prop?
Upvotes: 0
Views: 689
Reputation: 630
Dear, You can try to use this code
import ClientImg1 from "../../assets/static/img/client/client_img_1.png";
import ClientImg2 from "../../assets/static/img/client/client_img_2.png";
const themes = {ClientImg1, ClientImg2};
render() {
return (
<Child arrayData1={themes.ClientImg1} arrayData2={themes.ClientImg2}/>
)
}
in the
<Child arrayData1={themes.ClientImg1} arrayData2={themes.ClientImg2}/>
component or function page
you can call them by using this if function
function ClientSingleItem({arrayData1,arrayData2}) {
return (
<img src={arrayData1} alt="ClientImg" />
<img src={arrayData2} alt="ClientImg" />
.....
)
}
Upvotes: 1
Reputation: 4367
Here is an example of passing a value from an array from parent to grandchild. Notice how salutations is declared and assigned in the in the parent prop and propagated through the child to the grandchild.
This example be amended easily to pass the entire array instead of a single value within it.
render() {
return (
<div>
<h1>Passing props through the component tree...</h1>
<Parent greeting={salutations[0]}/>
</div>
);
}
}
const Parent = (props) => {
return (
<div>
<h2>Parent</h2>
<Child greeting={props.greeting} />
</div>
);
};
const Child = (props) => {
return (
<div>
<h3>Child</h3>
<Grandchild greeting={props.greeting} />
</div>
);
};
let salutations = ["hey", "what's up", "hello"]
const Grandchild = (props) => <h4>Grandchild - {props.greeting}</h4>;
ReactDOM.render(<App />, document.getElementById('app'));
Upvotes: 1