AtanasB
AtanasB

Reputation: 160

Call a function in a functional component in another file React

I have a login component that is in its own separate file, the component, however, needs to set a state in a parent component. Passing the state setter function as a props fails:

Uncaught TypeError: props.setLogState is not a function

Within the App(parent) component, this is my code:

{logState === 2 ? (
          <Login setLogState={setLogState} getTickers={getTickers} />
        ) : (
          ""
        )}

I am importing the Login component as follows: import Login from "./Components/login"; And in the Login component I export it as follows export default Login;

Within the Login component there is a function called login, which is called when the user clicks the login button in the same component, and part of the functionality is to call the parent setLogState and change the state. Below is how I call it.

  props.setLogState(1);

It seems that then login component does not read the props given. How do I fix this issue?

Upvotes: 0

Views: 680

Answers (1)

tgikf
tgikf

Reputation: 557

You must not be passing the setState function correctly. With the limited code you have provided it will be difficult to help analyze your specific problem, below a working example.

const { useState } = React;

const Child = (props) => {
  return (
    <input onChange={(e) => props.setStateProp(e.target.value)} />
  );
};
const App = () => {
  const [state, setState] = useState();

  return (
    <div>
      <Child setStateProp={setState} />
      {state && <p>State: {state}</p>}
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Upvotes: 1

Related Questions