Home > Net >  React - "Functions are not valid as a React child" when I return text from a function
React - "Functions are not valid as a React child" when I return text from a function

Time:04-02

I am learning React.js and I am not sure what is happening here. I want to have a function that returns a string isWaterBoiling() depending on the value of a variable. Then I want to render that string in UI but I am getting this error. I dont understand why this is happening, it doesnt make sense:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it. at div

Here is my code:

import { useState } from "react"

const App = () => {
    const [celsius, setCelsius] = useState()
    const [fahrenheit, setFahrenheit] = useState()

    const calculateFahrenheit = newCelsius => {
        setCelsius(newCelsius)
        setFahrenheit(((newCelsius * 9 / 5)   32).toFixed(2))
    }

    const calculateCelsius = newFahrenheit => {
        setFahrenheit(newFahrenheit)
        setCelsius(((newFahrenheit - 32) * 5 / 9).toFixed(2))
    }

    const isWaterBoiling = () => {
        return (parseFloat(celsius >= 100))
            ? "boiling"
            : "not boiling" 
    }

    return (
        <div className="bg-gray-800 h-full text-gray-300 p-4 text-center">
            <div className="font-semibold">Temperature Calculator</div>

            <div className="mt-4 space-y-4">
                <div className="flex gap-3 items-center">
                    <span className="flex-[5] text-right">Celsius:</span>

                    <input
                        value={celsius}
                        onChange={event => calculateFahrenheit(event.target.value)}
                        className="flex-[7] bg-gray-700 rounded-sm py-1 px-3"
                        type="text"
                    />
                </div>

                <div className="flex gap-3 items-center">
                    <span className="flex-[5] text-right">Fahrenheit:</span>

                    <input
                        value={fahrenheit}
                        onChange={event => calculateCelsius(event.target.value)}
                        className="flex-[7] bg-gray-700 rounded-sm py-1 px-3"
                        type="text"
                    />
                </div>
            </div>

            <div className="mt-4 italic text-gray-400">
                The water is { isWaterBoiling }
            </div>
        </div>
    )
}

export default App

CodePudding user response:

As the error mentions, you are not calling your isWaterBoiling function, but returning it. You need to change that bit of code to The water is { isWaterBoiling() }

  • Related