1

I want to call a function from a imported component in my parent react component.

My parent component:

import Customer from './Customer';  

function App() {

  return (
    <div className="App">
      <Container maxWidth="sm">
        <Grid container spacing={2}>
          <Grid item xs={6}>
            <Button onClick={Customer.showCustomers}>show customers</Button>
          </Grid>
        </Grid>
      </Container>
      <Customers />
    </div>
  );
}

My child component (customer):

function Customer() {
  const [showAllCustomers, setshowAllCustomers] = useState(false);

  function showCustomers() {
    setshowAllCustomers(true);
  }
  return (
    (...)
  );
}

How do I call a function from another component in functional react?

Or how do I change the state from another component (if thats the better approach)

All tutorials are about object-oriented react components, unfortunately.

David
  • 1,084
  • 12
  • 36

2 Answers2

3

React has a unidirectional, top-down data flow. Which means that horizontal communication is considered anti pattern. If you want to change a parent's state you should pass a handler to the child component to be executed at runtime

const Parent = () =>{
    const [foo, setFoo] = useState('foo')

    return <Child handler={setFoo} />
}

const Child = ({ handler }) => {
    const onClick = () =>{
        handler('baz')
    }

    return <button onClick={onClick}> Change Parent</button>
}

But in your case seems like the components do not have a hierarchical relationship. To share state in a decoupled way you should use Context API

Dupocas
  • 20,285
  • 6
  • 38
  • 56
2

State is generally passed down to child components via props

function Child (props) {
  // Set the default state
  const [showAllCustomers, setshowAllCustomers] =  useState(props.showAllCustomers);

  useEffect(() => {
    // Set the new state when props change
    setshowAllCustomers(props.showAllCustomers);
  }, [props.showAllCustomers]);

  return (
    (...)
  );
}
...
<Customer showAllCustomers={someVariable} />

When the showAllCustomers prop passed to Customer is changed internally the component will handle updating the local state.

James
  • 80,725
  • 18
  • 167
  • 237