Pinnci
Pinnci

Reputation: 453

How to call function in different component

I have a problem with calling a function. This function is in main App.js file and it's passed to different component as a prop. I need this function to get called if form validation returns true but my code doesn't work.

Function in App.js

  function getAlarm() {
    let message = document.getElementById("text").value;
    let hour = document.getElementById("hours").value;
    let minute = document.getElementById("minutes").value;

    //Add id to alarm
    let id;
    
    if(time.alarms.length > 0 ){
      id = Math.max(...time.alarms.map((alarm) => alarm.id)) + 1
    }else{
      id = 1;
    }

    //Create new alarm object
    const newAlarm = {
      id: id,
      message: message,
      hour: hour,
      minute: minute
    };

Passed to component as a prop

<SetAlarm getInfo={getAlarm} />

In this component I have little form ,which have some validation. For better understanding I'll show you form and these functions too.

Form

<form onSubmit={validateForm}>
    <FontAwesomeIcon 
      icon={faTimesCircle} 
      className="closeIcon"
      onClick={() => setAlarm(false)} />

    <h3>Please set your alarm</h3>

    <label htmlFor="text">Message</label>
    <input type="text" id="text" autoComplete="off" autoFocus="on" />

    <div className="flex">
      <div className="inputNumber">
         <label htmlFor="hours">Hour</label>
         <input type="number" id="hours" value={validate.hours} onChange={updateHours} />
         <div id="errHours"></div>
      </div>
                            
      <div className="inputNumber">
         <label htmlFor="minutes">Minute</label>
         <input type="number" id="minutes" onChange={updateMinutes} />
         <div id="errMinutes"></div>
      </div>
    </div>
    <button onClick={validateForm}>SET ALARM</button>
 </form>

Input elements have onChange function which is sending it's value to state. Depending on this value validation signal will show up. (I mean if condition returns false, red border will show up,or warning under input)

const [validate,setValidate] = useState({
    message:'',
    hours:'',
    minutes:''
})

function updateHours(e){
    let value = e.target.value;
    let hours = document.getElementById('hours');
    let errHours = document.getElementById('errHours');

    setValidate(prevState => ({
        ...prevState,
       hours:value
    }))

    if(Number(hours.value) > 23){
        hours.style.border='1.5px solid red';
        errHours.innerHTML='<span>Please enter 1-23</span>'
    }else{
        hours.style.border='1px solid grey'
        errHours.innerHTML='';
    }
}

function updateMinutes(e){
    let value = e.target.value;
    let minutes = document.getElementById('minutes');
    let errMinutes = document.getElementById('errMinutes');

    setValidate(prevState => ({
        ...prevState,
        minutes:value
    }))

    if(Number(minutes.value) > 59){
        minutes.style.border='1.5px solid red';
        errMinutes.innerHTML='<span>Please enter 1-59</span>';
    }else{
        minutes.style.border='1.5px solid grey';
        errMinutes.innerHTML='';
    }
}

And finally validateForm() function. As you can see it's called on form onSubmit. It's supposed to check if values of state meet the condition. If condition returns false,you are not able to submit this form ,so no alarm will be added. But if condition returns true ,i want to call that function which I'm sendind as a prop.

function validateForm(e){
    e.preventDefault();
    if(Number(validate.hours) > 23 || Number(validate.hours) < 1){
        return;
    }

    if(Number(validate.minutes) > 59 || Number(validate.minutes) < 1){
        return;
    }

    //This is not working. If all conditions returns true, nothing happens.
    return () => props.getInfo;

    //I tried it like this too
    // return props.getInfo();

    //Or like this;
    //return props.getInfo;

    //To be sure it's working I've tried simple console log and it's working
    //return console.log('hello');
}

According to my last try with that console log, I assume I'm just not calling this function properly. Sorry for that long question and code examples,but I wanted to be sure everyone will get what I'm talking about. Thanks :)

Upvotes: 0

Views: 1187

Answers (1)

Monzoor Tamal
Monzoor Tamal

Reputation: 810

<SetAlarm getInfo={getAlarm} />

in SetAlarm component

const SetAlarm = ({getInfo}) => {

  const validateForm = () => {
     getInfo(); // Do whatever you like to do with this 
  }

  return (
     <form onSubmit={validateForm}>
        

        <label htmlFor="text">Message</label>
        <input type="text" id="text" autoComplete="off" autoFocus="on" />

       
        <button type="submit">SET ALARM</button>
     </form>

  )

}

Upvotes: 1

Related Questions