reactjsfunctioncomponentsonchangeonkeypress

React function in a component


I am working in React with components, but I am not getting functions working in the Input component.

I have tried searching on component and onChange or onKeyPress but they do not show what I need. Maybe I'm searching wrong? I did get the component Button working, just not Input.

The code for the component is simple.

import React from 'react';
import styles from './Input.module.css';

function Input({inputText}) {
    return <input type='number'
                  placeholder={inputText}
                  className={styles.input}
    />
}

export default Input;

The full code I want to use for component Input is as follows.

import React, {useState} from 'react';
import styles from './Food.module.css';
import axios from 'axios';
import Nutrients from '../../components/nutrients/Nutrients'
import {ReactComponent as LoadingIcon} from '../../assets/loading.svg'
import Button from "../../components/button/Button";
import Input from "../../components/input/Input";

function Food() {
    const [food, setFood] = useState(null);
    const [calories, setCalories] = useState('');
    const [disabled, setDisabled] = useState(false);
    const [error, setError] = useState('');
    const [loading, toggleLoading] = useState('');

    async function foodData() {
        setError('');
        toggleLoading('true')

        try {
            const result = await axios.get(`https://api.spoonacular.com/mealplanner/generate?apiKey=${process.env.REACT_APP_API_KEY}&timeFrame=day&targetCalories=${calories}`);
            setFood(result.data);
        } catch (error) {
            setError('Oops... something went wrong. Please try again.');
            console.log('Something went wrong while retrieving the data.', error);
        }
        toggleLoading(false);
    }

    function handleChange(e) {
        setCalories(e.target.value);
    }

    function handleKeyPress(e) {
        if (e.key === 'Enter') {
            if (disabled) {
                return;
            }
            foodData();
            setDisabled(true);
        }
    }

    return (
        <>
            {error && <p className={styles.error}>{error}</p>}
            <div>
                <section className={styles.food}>

                    <Input
                        inputText='Enter caloriessss'
                        onChange= {handleChange}
                        onKeyPress={handleKeyPress}
                    />
                    <Button
                        onClick={() => {
                            foodData();
                            setDisabled(true);
                        }}
                        buttonText='Click for your daily meals'
                    />
                </section>
                {loading && <LoadingIcon className={styles.loader}/>}
                {food && <Nutrients mealsData={food}/>}
            </div>
        </>
    );
}

export default Food;

The thing I want is for the two functions onChange and onKeyPress to work in the Input component.

Anyone has any ideas? I also tried using () and ''.


Solution

  • Because you don't use props onChange and onKeyPress in Input component. Just add it like this:

    function Input({ inputText, onChange, onKeyPress }) {
      return (
        <input
          type="number"
          placeholder={inputText}
          className={styles.input}
          onChange={onChange}
          onKeyPress={onKeyPress}
        />
      );
    }
    

    Or shorter way:

    function Input({ inputText, ...props }) {
      return (
        <input
          type="number"
          placeholder={inputText}
          className={styles.input}
          {...props}
        />
      );
    }