Search code examples
javascriptmaterial-uipass-by-value

Issue Passing Value that Needs to be Printed


I want to call a function with 3 inputs. 2 of them are numbers and one is a string. The two numbers are further passed but that is not the issue. I want the string to be printed within the element.

I believe that this is an issue is with passing the parameter to an html part of the code but I don't know how to do it.

import Typography from '@material-ui/core/Typography';    


export function myfunction(name, min max){
    const midpoint = Math.ceil((min + max)/2)
    return(
    <div>
        <Typography id="input-slider">
            name //this is where I want name to be
        </Typography>
    <div/>
    )
}

In a second file I call this

function main(){
    return(
        <div>
            {myfunction(MYNAME, 0, 10)
        <div/>
    )
}

Solution

  • You are defining a function myFunction which is a react component. A react component is basically just a function that accepts a properties object as first argument and returns JSX (html for react).

    The first little stone on your way to success here is that you accept three arguments in the myFunction function.

    So here is how a correct react component could look like

    function MyAwesomeComponent({ name, min, max }) {
      const midpoint = Math.ceil((min + max) / 2);
      // use curly brackets around a variable as in {midpoint} to print the value
      return <Typography id='input-slider'>{name}</Typography>;
    }
    

    If we want to use it in another react component, as you do with the main function. Write is as a react component as well.

    function Main() {
      return <MyAwesomeComponent name={'YourName'} min={0} max={10} />;
    }
    

    I hope this solves your issue. For a better understanding of how to write react components I can highly recommend to read more in detail about this topic in the official react documentation.