Giving major props to your components

 Another day and another issue with React. Today I had a simple issue:

import { useState, useEffect } from "react";
import symbols from "./Symbols.js"

const DrawSymbol = (prop) => {
const [state, setState] = useState("");

  useEffect(() => {
    const g = symbols.find((obj) => {     
    return obj[prop];
    });

setState(g.url);

},[]);

return <div>{state}<div>

};
 

As you can see above, I am passing 'prop' as a property to my component such that it will a 'find' on an object in the array called symbols. This object will be set as state and rendered inside a DIV. Now if you have some experience with ReactJS you know the issue already, but I'm new, so bare with me. When executed, this function failed. The result was an undefined object being returned.

The solution, after a brain twisting session, became clear that I was using the word prop literally. Prop is actually an object that represents all attributes passed to the component.  Funny enough, early React tutorials explained the use of prop, but I never registered that prop was an object and not just a shorthand for property. Nevertheless, if my component is <DrawSymbol mana="2B"> the solution is to access the string as a property of prop. In this case prop.mana will give the string value. 

 


Post a Comment

Previous Post Next Post