Home > OS >  How to Access Props in React Functional Component Using Props.Match.Params
How to Access Props in React Functional Component Using Props.Match.Params

Time:10-04

Props seems to be passed successfully from parent component to child component based on the log, but I'm getting a typeerror undefined message when attempting to pull a picture for display from a specific property.

Parent.js

...
const [myState, setMyState] = useState([]);

useEffect( () => {
  axios
  .get('/gogetit')
  .then(res => {
    setMyState(res.data);
  })
  .catch(err => {
    console.log(err);
  })
}, []);

...

<BrowserRouter>
...
  <Route path="/child/:id" exact 
    render={(routerProps) => (
      <Child {...routerProps} 
        myState={myState}
      />
    )} 
  />
...

Child.js

const Child = (props) => {

  useEffect(() => {
    console.log(props.myState); //ok [ {id: '1', src:'url'}, {id: '2', src:'url2'} ]
    console.log(props.match.params.id); //ok 0
    console.log(props.myState[props.match.params.id]); //ok {id: '1', src:'url'}
    console.log(props.myState[props.match.params.id].src); //not ok undefined
  })

  return
  ...
    <img src={props.blurbs[props.match.params.id].src} />
...

CodePudding user response:

The myState state array is initially empty, so from the initial render cycle to whenever the GET request resolves and populates the myState array, myState[any index] will be undefined and attempting to access a property of undefined will throw an error.

Use a guard-clause/null-check

console.log(
  props.myState &&
  props.myState[props.match.params.id] && 
  props.myState[props.match.params.id].src
);

or Optional Chaining operator

console.log(props.myState?.[props.match.params.id]?.src);

The idea here is that each property access of any potentially null/undefined object is checked to be truthy prior to accessing into it.

...

<img src={props.blurbs?.[props.match.params.id]?.src} />
  • Related