Search code examples
reactjsreact-hookscreate-react-appreact-propsreact-functional-component

Returning a component inside a functional component


import React from "react";
import HeroAsideItems from "./components/HeroAsideItems";
import "./css/heroAsideCircles.css";

function HeroAsideCircles(props) {
 
  const renderHeroAsideItems = () => {
    // Turn the prop object into an array of its keys using Object.keys(props)
    //Then map/loop over the array of keys returned by Object.keys
    //The argument "keys" holds and array of keys and "i" hold the index of the array so it is the iterable. It will increase for every key in the array starting at 0.
    Object.keys(props).map((keys, i) => {
      // Test for valid prop inputs. I want all valid props to follow the naming convention of `hoverTxt${someNumber}`
      // validPropCount takes the key argument passed by map (which holds the keys of the prop object in an array) and checks to see if it includes `hoverTxt${and some number within the amount of entries in the array}`
      // validPropCount will return true if it includes those values or false if it does not
      const validPropCount = keys.includes(`hoverTxt${i + 1}`);
      //If validPropCount returns true return and assign the <HeroAsideItems /> component the current prop value being passed in the loop to the component's hoverTxt (which is responsible for the text of the component)
      if (validPropCount) {
        console.log("valid");
        console.log(Object.values(props)[i]);
        return <HeroAsideItems key={i} hoverTxt={Object.values(props)[i]} />;
        // else if validPropCount returns false do not return a component
      } else {
        console.log("not valid");
      }
    });
  };

  return (
    <div className="hACContainer">
      {renderHeroAsideItems()}
    </div>
  );
}

export default HeroAsideCircles;

I'm trying to return the component inside the renderHeroAsideItems function. This is how i tried to do it but it doesnt work. What would be the correct syntax


Solution

  • You are not returning the result of Object.keys(props).map((keys, i) => {}).

    It should be return Object.keys(props).map((keys, i) => {})