Re-render class in React

react re-render when props change
react lifecycle
react force child component to re-render
react re-render functional component
forceupdate react example
forceupdate react hooks
react force update functional component
react class component

new to React, I'm testing to write a small program where you select a name in a list, and then a proverb should be displayed. The event handler handleAuthorClick is called, and setState is also called, but the new text is not displayed.

Why?

class AuthorList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: -1,
      text: "When in Rome do as the Romans",
    }
  }

  handleAuthorClick()
  {
       let txt = "initial value";
       var sel = document.getElementById("author-list"); 
       switch (parseInt(sel.value))
        {
          case 12 : txt = "When in Rome do as the Romans"; break;
          case 33: txt = "If you tell the truth, you don't have to remember anything.";break;
          case 256: txt = "History will be kind to me for I intend to write it";break;
          default:;
        }
       this.setState({text: txt});
  }

  render() {
      return (
        <div className="author-list">
          <h2>Author List</h2>
          <select id='author-list' name='author-list' size='15' onClick={() => this.handleAuthorClick()>
             <option value="12">Unknown</option>
             <option value="33">Mark Twain</option>
             <option value="256">Winston Churchill</option>
          </select>
          <h2>Proverbs</h2>
          {this.props.text}
        </div>
      );
    }
  }

class ProVerbMain extends React.Component {
      render() {
      return (
        <div className="proverb">
          <h1>Dans proverbs</h1>
          <div className="author-list">
            <AuthorList text = 'Initial value'/>
          </div>
        </div>
      );
    }
  }

ReactDOM.render(<ProVerbMain />, document.getElementById('root'));

Use this.state.text instead of this.props.text, because it's a local state of your component. When you use this.props.text your component doesn't know the new state for new render. You should use onChange() event instead of onClick() in select option

React.Component – React, Re-render component when state changes. Any time a React component state has changed, React has to run the render() method. class App extends React. useCallbackuseMemo step#1 — Start with default implementation — no useCallback/useMemo. It renders the TickerComponent for each ticker in step#2 — Leverage useMemo and useCallback. We don’t want the TickerComponent to re-render every-time its parent gets Final step — use functional form of

this should work for you , use onChange rather than onClick. also you were using class methods handleAuthorClick() and not even binding them to class's this as function have their own this scope , you can't access class members from inside that function, that's why either use () => {} or use .bind(this) in class's constructor

EDIT: https://reactjs.org/docs/forms.html#the-select-tag

import React, { useEffect } from "react";
import ReactDOM from "react-dom";

import "./styles.css";
class AuthorList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: -1,
      text: "When in Rome do as the Romans"
    };
  //this.handleAuthorClick = this.handleAuthorClick.bind(this); 
  }

  handleAuthorClick = e => {
    let txt = this.props.text;
    console.log(e.target.value);
    switch (e.target.value) {
      case "12":
        txt = "When in Rome do as the Romans";
        break;
      case "33":
        txt = "If you tell the truth, you don't have to remember anything.";
        break;
      case "256":
        txt = "History will be kind to me for I intend to write it";
        break;
      default:
    }
    // alert(txt);
    this.setState({ text: txt });
  };

  render() {
    return (
      <div className="author-list">
        <h2>Author List</h2>
        <select name="author-list" size="15" onChange={this.handleAuthorClick}>
          <option value="12">Unknown</option>
          <option value="33">Mark Twain</option>
          <option value="256">Winston Churchill</option>
        </select>
        <h2>Proverbs</h2>
        {this.state.text}
      </div>
    );
  }
}

class ProVerbMain extends React.Component {
  render() {
    return (
      <div className="proverb">
        <h1>Dans proverbs</h1>
        <div className="author-list">
          <AuthorList text="Initial value" />
        </div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<ProVerbMain />, rootElement);

demo : https://codesandbox.io/s/react-hooks-counter-demo-yj3s5

4 methods to force a re-render in React, The beauty of React components is that they automagically render and update There are multiple ways to force a React component render but they are is now the responsibility of a separate Model class in vanilla JS. In React this means calling the render function, in the real DOM this means re-painting the UI. The good news is that you don't have to worry too much about performance bottlenecks of UI redraws. React already optimizes this for you.

You've to use state instead of props.

import React from "react";

class AuthorList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: -1,
      text: "When in Rome do as the Romans"
    };
  }

  handleAuthorClick() {
    let txt = "initial value";
    var sel = document.getElementById("author-list");
    switch (parseInt(sel.value, 10)) {
      case 12:
        txt = "When in Rome do as the Romans";
        break;
      case 33:
        txt = "If you tell the truth, you don't have to remember anything.";
        break;
      case 256:
        txt = "History will be kind to me for I intend to write it";
        break;
      default:
    }
    //alert(txt);
    this.setState({ text: txt });
  }

  render() {
    const { text } = this.state;
    return (
      <div className="author-list">
        <h2>Author List</h2>
        <select
          id="author-list"
          name="author-list"
          size="15"
          onClick={() => this.handleAuthorClick()}
        >
          <option value="12">Unknown</option>
          <option value="33">Mark Twain</option>
          <option value="256">Winston Churchill</option>
        </select>
        <h2>Proverbs</h2>
        {text}
      </div>
    );
  }
}

class ProVerbMain extends React.Component {
  render() {
    return (
      <div className="proverb">
        <h1>Dans proverbs</h1>
        <div className="author-list">
          <AuthorList text="Initial value" />
        </div>
      </div>
    );
  }
}

export default ProVerbMain;

And here is your working sandbox link https://codesandbox.io/s/still-grass-r5iz9/

Force a React Component to Re-Render, ComponentType<any>) { return class WithStore extends PureComponent<{}, {​lastUpdated: number}> { constructor(props: React.ComponentProps<any>)  React render is one of the many component lifecycles that a React component goes through. The render method is required whenever you’re creating a new React component. React render requires you to return a value. This may either be null, undefined or JSX markup.

Can you force a React component to rerender without calling , In your component, you can call this.forceUpdate() to force react rerender. Learn react force rerender by kicking off components. "Mounting" is when React "renders" the component for the first time and actually builds the initial DOM from those instructions. A "re-render" is when React calls the function component again to get a new set of instructions on an already mounted component.

React Force Rerender, React achieves a fast and responsive UI by re-rendering components on every state change Always extend class components from React. If you have something in your UI that generates the same alert each time it is clicked, by default react doesn't re-render the DOM so the screen reader doesn't announce the change. Setting a unique key makes it work. Maybe the downvote was because it still involves setting state. But forcing a re-render to DOM by setting key is golden!

Why Does React Components Re-Render, Re-render. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16, class Todo extends  To define a React component class, you need to extend React.Component: class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } } The only method you must define in a React.Component subclass is called render (). All the other methods described on this page are optional.

Comments
  • text is in state, not props. Also there's almost never any good reason to dig into the DOM to get values like this, at least for simple stuff like normal form elements.
  • Text property value won't change after setState, try writing this.state.text || this.props.text. You should use onChange instead of onClick in select tag.
  • Don't mix the state and props name. And yes onChange() should be the candidate to work here not onClick().
  • Actually yes, you can get rid of initial text property and use only state object to display your text.
  • This doesn't address the biggest issue (and the OP states it works, although I agree in should be onChange).
  • Yeah, but I think his issue is using this.props.text in render
  • Yes, as I said in my comment, and you edited your question to answer.
  • Yes, I am a newbie. I just want to help