0

I have a function in my Numbers component that should return the state however it returns [object,object] I cant see what i've done wrong? I've written a function in Numbers, that returns another function in my apps component!

import React, { Component } from 'react';
import Numbers from './Numbers'
import './App.css';

class App extends Component {
  constructor(props){
    super()
    this.state={
      calcValue:0
    }
  }

  takeValue = (n) => {
    alert(n)
  }

  render() {
    return (
      <div className="App">
        <Numbers submit={(n) => this.takeValue(n)} numberValue={1}/>
      </div>
    );
  }
}

export default App;

Number component:

import React, { Component } from 'react';
import propTypes from 'prop-types';

class Numbers extends Component {
  constructor(props){
    super();
    this.state={
      numberValue:6
    }
  }

  submit = (n) => {
    this.props.takeValue(this.state.numberValue)
  }

  render() {
    return (
      <div>
        <button value={this.state.numberValue} onClick={this.props.submit}>
          {this.props.numberValue}
        </button>
      </div>
    )
  }
}

// Completed.propTypes={
// test:propTypes.string.isRequired

export default Numbers

2 Answers 2

3

You are not understanding concept of passing the props. you need to differentiate what you are passing into child component and how you want to call the parent from child.

Change

onClick={this.props.submit}

to

 onClick={this.submit}

and

 submit=(n) => {    
       this.props.takeValue(this.state.numberValue)    
    }

to

  submit = (n) => {
    this.props.submit(this.state.numberValue)
  }

onClick={this.props.submit} will call parent component not the child one

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Yes I have seen my mistakes. I am new to React.
@Lee yes it happens :)
0

Thanks I have found my error! Should be this.submit not this.props.submit Also I needed to call the takeValue function

Thanks

2 Comments

yep. I think this is what you're looking for: stackblitz.com/edit/react-dobewq
This section is reserved for answers, you can thank @Just code by accepting his answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.