Home > other >  React: Pass result of function (return) as props. But Child component receives as undefined?
React: Pass result of function (return) as props. But Child component receives as undefined?

Time:12-07

I have the following setup where I have a function tomorrowDate() that returns a date. I want to pass this as a prop. But on the Child component this is undefined. I assume that there is something going wrong with passing the returned value.

How should I do that?

const Parent = () => {
    const tomorrowDate = () => {
        return new Date()
    }


    return (

        <Child
        minDate={tomorrowDate()}
        test={"test"}
        />
    )
}


class Child extends Component {

    componentWillMount() {
        console.log("props are", this.props)
    }

    render(){
        // DO STH
    }
}

The output is...

props are {test:"test", minDate=undefined}

CodePudding user response:

I'm not sure what the issue is but I've created a snippet that does what you want.

function Child({ minDate }) {
  return <div>{minDate.toLocaleString()}</div>;
}

function Parent() {
  const tomorrowDate = () => {
    return new Date();
  };

  return (
      <Child minDate={tomorrowDate()} />
  );
}

// Ignore this
ReactDOM.render(
  <Parent />,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I just copy and pasted your code and if you see the result of this snippet, it's working without any problem.

const Parent = () => {
  const tomorrowDate = () => {
    return new Date()
  }

  return (
    <Child 
    minDate = {tomorrowDate()}
    test = {"test"}
    />
  )
}

class Child extends React.Component {
  componentWillMount() {
    console.log("props are", this.props)
  }

  render() {
    return null; // DO STH
  }
}

ReactDOM.render( <Parent / > , document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

pass tomorrowDate without tomorrowDate() and use as props.minDate() inside child component

  • Related