'How to access props from Parent Component inside the Child Class Component ? (specifically for componentDidMount)?
I want to use the {prop.idno} from parent to child in componentDidMount() fetch call URL . How do I make use of idno in the URL to call different posts pages.
Is there a way to write it like this?
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?userId= ${this.prop.idno}`
);
Parent Component :
return (
<>
<TogglePosts idno = {user.id}/>
</>
)
Child Component:
export class TogglePosts extends Component {
constructor(props){
super(props);
this.state = {
on: false,
data: [],
loaded: false,
};
}
toggle = () => {
this.setState({
on: !this.state.on,
});
};
async componentDidMount() {
console.log("comp did mount");
try {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?userId=1`
);
const data = await response.json();
console.log(data);
this.setState({ data: data, loaded: true });
} catch (err) {
console.log(err);
}
}
Solution 1:[1]
You can try editing your response similar to this.
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?userId= ${this.props.idno}`
);
Note that I've used `(tilde) instead of "(double quotes)
Also use props instead of prop
Solution 2:[2]
Try this:
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?userId= ${this.props.idno}`
);
Template literal(``) is the ability to include expressions and variables within a string.
Solution 3:[3]
Can you try accessing it using props.idno in the TogglePosts Component? In the fetch statement you can do something like fetch(`https://jsonplaceholder.typicode.com/posts?userId=${props.idno}`);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sampurna |
| Solution 2 | jcoder |
| Solution 3 |
