Toni Michel Caubet
Toni Michel Caubet

Reputation: 20163

Call other component's method

I have this little component:

import React from 'react';

const Footer = (props) => {
    return (
    <footer className="top">
      <p>{props.items} items in your menu</p>
    </footer>
  )
}

const updateItems = (n) => {
    this.props.items = this.props.items + n;
};

Footer.propTypes = {
  items: React.PropTypes.string.isRequired
};

export default Footer;

And from the main component:

// All irrelevant imports
import Footer from './Footer';

class App extends React.Component {
   // All the irrelevant vars and methods

   removeFish = (key) => {
        const fishes = {...this.state.fishes};
        fishes[key] = null;
        this.setState({ fishes });
        Footer.updateItems(-1); // <-- This is not updating the items count in the footer component
    };
}

My Footer.updateItems doesn't seem to update the value, even that the console fires no errors and the app complies,

Which would be the correct way?

Upvotes: 0

Views: 95

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281646

Firstly updateItems is not a function of Footer component

Secondly, you should not change the props directly, you need to change your structuring and handling the updates in the App component and let the Footer be pure as it is a stateless component

import React from 'react';

const Footer = (props) => {
    return (
    <footer className="top">
      <p>{props.items} items in your menu</p>
    </footer>
  )
}

Footer.propTypes = {
  items: React.PropTypes.string.isRequired
};

export default Footer;

App

// All irrelevant imports
import Footer from './Footer';

class App extends React.Component {
   // All the irrelevant vars and methods

   removeFish = (key) => {
        const fishes = {...this.state.fishes};
        fishes[key] = null;
        this.setState({ fishes });

        this.updateItems(-1); 
    };
    updateItems = (n) => {
        this.setState((prevState) => ({items: prevState.items + n}))
     };
    render(){
         return (
               <Footer items={this.state.items}/>
         )
    }
}

Upvotes: 2

Related Questions