0

I am trying to make a recursive class component to check if an input is a palindrome or not. but when I am trying to call the palindrome function inside of this function its starts invoking indefinitely. using vanilla js this method worked just fine. what I am doing wrong here? and how to change the output when the input field is empty.

import React, { Component } from "react";

import "./App.css";

export default class App extends Component {
  state = { data: "", palindrome: "" };

  inputHandeler = (e) => {
    this.setState({ data: e.target.value });
  };
  palindrome = () => {
    if (this.state.data.length === 1 || this.state.data.length === 0) {
      this.setState({ palindrome: "this is palindrome" });
    } else if (
      // input abba console.log("indefinitely ")
      this.state.data[0] === this.state.data[this.state.data.length - 1]
    ) {
      this.palindrome(this.state.data.slice(1, this.state.data.length - 1));
    } else {
      this.setState({ palindrome: "this is not palindrome" });
    }
  };

  render() {
    return (
      <div className="container">
        <h1> Palindrome Checking App</h1>
        <div className="app">
          <div className="inputfield">
            <label name=" palindrome ">
              Input text to check if it is a palindrome:
            </label>
            <input id="palindrome " type="text" onChange={this.inputHandeler} />
            <button onClick={this.palindrome}>Check</button>
          </div>
          <div className="output">{this.state.palindrome}</div>
        </div>
      </div>
    );
  }
}
2
  • 1
    this.palindrome() takes no arguments, so I'm not sure what you expect this line to accomplish: this.palindrome(this.state.data.slice(1, this.state.data.length - 1)); Commented Nov 8, 2022 at 23:19
  • 1
    palindrome() doesn't take any parameters. setState schedules an update for sometime in the future with the new state. It doesn't do anything immediately. Commented Nov 8, 2022 at 23:19

1 Answer 1

1

You need to define your palindrome method to not rely on the current state.

palindrome = (data: string[]) => {
  if (data.length === 1 || data.length === 0) {
    this.setState({ palindrome: "this is palindrome" });
  } else if (
    // input abba console.log("indefinitely ")
    data[0] === data[data.length - 1]
  ) {
    this.palindrome(data.slice(1, data.length - 1));
  } else {
    this.setState({ palindrome: "this is not palindrome" });
  }
};

render() {
  return (
    ...
    <button onClick={() => this.palindrome(this.state.data)}>Check</button>
    ...
  );
}
Sign up to request clarification or add additional context in comments.

Comments

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.