Passing a number to a function in react js

Viewed 1455

I want to pass a number to the function.I follow same way to pass both string and integer values. I can pass the string value. But I can't pass the integer value in that way.

This is my lesson2.js file

import React from 'react'

class lesson2 extends React.Component{

    constructor(props){
        super(props);
        this.state = {counter:1}
    }

    add(){
        this.setState(function(state,props){
            return{
                counter: state.counter + props.increment
            };
        })
    }

    render(){
        return(
        <div>
            Counter : {this.state.counter}</div>
        );
    }
}

export default lesson2

This is my App.js

import React from 'react';
import './App.css';
import Variable from './Components/variable_dec'
import Lesson2 from './Components/lesson2'

function App() {
  return (
    <div className="App">

        <p>
          <Variable name='D' />
          <Lesson2 increment={10}/>
        </p>

    </div>
  );
}

export default App;

This is my output. But in my correct output should be Counter : 11. The problem is that the increment value doesn't add to the counter. So hope your help to solve my problem.

enter image description here

3 Answers

You have defined your function add(), but you never called it anywhere in your lesson2.js file. Hence, the counter is not updated with the prop you pass.

Call add() function just after the component mounted using componentDidMount().

So, your lesson2.js file should be as follows.

import React from 'react';

class lesson2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = { counter: 1 };
  }

  componentDidMount() {
    this.add();
  }

  add() {
    this.setState(function (state, props) {
      return {
        counter: state.counter + props.increment,
      };
    });
  }

  render() {
    return <div>Counter : {this.state.counter}</div>;
  }
}

export default lesson2;

The add() function is not used at all inn Your code

i can't see where you called the add function. If you want to initialize your counter with increment, you should set your state with props.increment in constructor instead of setting it to 1.

this.state = {counter:props.increment}
Related