How to make a change in button according to state value in React

You can make a change in button according to state value in React easily in 2 steps :

1- Create a state in React & set values under it.

2- Create a button & attached that to state value.

create a state in React & set values under it.

class TodoApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = { items: [], text: '' };       --> State Creation                      
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  render() {
    return (
      --->Make input of value  
    );
  }

  handleChange(e) {
    this.setState({ text: e.target.value });
  }

  handleSubmit(e) {
    e.preventDefault();
    if (this.state.text.length === 0) {
      return;
    }                               -->Setting Values in State
    const newItem = {
      text: this.state.text,
      id: Date.now()
    };
    this.setState(state => ({
      items: state.items.concat(newItem),
      text: ''
    }));
  }
}

I have divided above code in three sections , first one is state creation , second one is getting values for state , third one is setting value in state.

Create a button & attached that to state value.

class TodoApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = { items: [], text: '' };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);   --State Creation
  }

  render() {
    return (
      <div>
        <h3>TODO</h3>
        <TodoList items={this.state.items} />
        <form onSubmit={this.handleSubmit}>
          <label htmlFor="new-todo">
            What needs to be done?
          </label>
          <input
            id="new-todo"
            onChange={this.handleChange}          -->Taking input Of Value
            value={this.state.text}
          />
          <button>
            Add #{this.state.items.length + 1}  -->Making button & attaching to state value.
          </button>
        </form>
      </div>
    );
  }

  handleChange(e) {
    this.setState({ text: e.target.value });
  }

  handleSubmit(e) {
    e.preventDefault();
    if (this.state.text.length === 0) {
      return;
    }
    const newItem = {
      text: this.state.text,
      id: Date.now()
    };
    this.setState(state => ({
      items: state.items.concat(newItem),
      text: ''
    }));
  }
}

In above code you can see , state value is attached to button like –

<button>
  Add #{this.state.items.length + 1}  -->Making button & attaching to state value.
</button>

Just after giving the name of button add ‘#{ }’ & between curly braces mention the state items.

Thank you for reading !