Search code examples
reactjsformscomponents

How to render a function im passing down as a prop to a child component in React?


I'm trying to show a list of times available in a form as options, I was able to so it using useState but now im trying it with a reducer and I can't figure out why its not working. I pass the function down as a prop and then call it int he child component but the options element doesn't render and i'm not recieving any errors in the browser. I can add more information if its needed. I tried to condense it.

//parent component

import BookingForm from '../components/bookingForm'
import { useState,useReducer } from 'react'

function Reservations(){

    const initialState = ["17:00","18:00","19:00","20:00","21:00"]

    const updateTimes = (availableTimes,action)=>{
        return availableTimes
    }
    const initializeTimes= () =>{
        {initialState.map((times) =>{
            return(
                <option key={initialState}>{times}</option>  
                )
            }
        )}  
    }


    const [availableTimes, dispatch] = useReducer(updateTimes, initializeTimes);

    return(
        <>
            <Nav/>
            <header>
                <div>
                    <h1>Book a table</h1>
                    <h2>Little Lemon</h2>
                </div>
            </header>
            <div>
                {<BookingForm
                initializeTimes={initializeTimes}
                />}
            </div>
            {<Footer/>}
        </>
    )
}

export default Reservations

//Child component

 import { useState } from "react";

function BookingForm(props){

(...form elements)
return(
     <div>
       <label htmlFor="res-time">Choose time</label>
          <select id="res-time">
              {props.initializeTimes()}
          </select>
     </div>
)

I've pretty much tried doing most things i could think of as I've googled how to pass functions as props to children but have not been successful.


Solution

  • change initializeTimes function:

      const initializeTimes = () => {
       return initialState.map((times) => {
        return (
         <option key={times}>{times}</option>
        );
       });
      }