Search code examples
reactjsreact-functional-component

Error while passing data from a child to parent component in reactjs


As soon as ObjectRow's onchange1 and onchange2 are triggered, it gives a runtime error of sendColor is not a function(same for sendName) . As my form submit button is present in the parent component of ObjectRow, I am trying to get the data of ObjectRow's input in my parent component so as to proceed further. Is it the right way to do so or any other method better?

     const rows = []
            for (let i = 0; i < rewards; i++) {
        
                rows.push(<ObjectRow key={i} num={i} sendColor={sendColor} sendName={sendName} />);
                console.log(angle)
            }
     

    const sendColor = (data) => {
                console.log(data)
            }
        
            const sendName = (data) => {
                console.log(data)
            }




  <form onSubmit={onsubmit}>
            {rows}
        <div className='flex justify-center'> 
<button className={`${rewards > 0 ? 'bg-red-700 w-4/12 rounded-md  p-2 font-normal text-lg text-white' : 'hidden'}`}>Submit</button>
</div> 
</form>
    

Below is the Objectrow component:

    import React from 'react'
    import {useState} from 'react'
    
    function ObjectRow({num,sendColor,sendName}) { 
    
        
      const [name, setName] = useState('')
      const [color,setColor]=useState('')
       
      
        
      const handlechange1=(e)=>{
          
            setColor(e.target.value)
            sendColor(color)
        }
    
      const handlechange2 = (e) => {
    
         setName(e.target.value)
          sendName(name)
      }
    
       
      
       
      
    
       
      return (
       <>
    <div className='text-xl font-semibold text-violet-700'>Reward{num+1}</div>
                 
                  <label>Reward Name</label>
                  <input type='text'
                  name="rewardName" 
                    onChange={handlechange2}
                    value={name} 
                   className='bg-slate-400 my-4  mx-2'>
                    </input>                                  
            
             
                  <label>Reward Color</label>
                  <input type='text' 
                  name="rewardColor"
                 onChange={handlechange1} 
                   value={color}
                   className='bg-slate-400 my-4  mx-2'>
                  </input>              
              
               
              <hr /> 
       </>
      )
    }
    
    export default ObjectRow

Solution

  • Try defining sendColor and sendName above your declaration of rows