How do you change what jsx blocks are being rendered from inside a same class?

react: render conditionally from props
react conditional render multiple elements
conditional rendering react native
react native if condition in render
react functional components
react render component onclick
react: use a ternary expression for conditional rendering
react conditional rendering best practices

I'm still learning the basics of React, and I wanted to do something that caught my attention. It's about rendering two things. Is it possible or even plausible to just change what is rendered with a function, and then calling the functions separately with a button or timer?

This is a sample code, to show how it would render two completely different things. It is supposed to render a button that says "State: On" or "State: Off". And when you click the button the state changes. But also, the whole render method is switched... or at least that's what's supposed to be happening.

class Flicker{
    constructor(props){
        super(props);
        this.state = {mode: "on"};
    }
    flipOn(){
        this.setState({mode: "on"})
    }
    flipOff(){
        this.setState({mode: "off"})
    }
    if (this.state.mode == "on"){
        render() {
            return(
                <button onClick={this.flipOn}>State: On</button>
            );
        }
    } else if (this.state.mode == "off"){
        render() {
            return(
                <button onClick={this.flipOff}>State: Off</button>
            );
        }
    }
}
export default Flicker;

If this isn't the correct way to do this type of changes in what jsx gets rendered on the app, how should it be done?

You have the right idea - but in a class there is only one render method. Your logic does belong inside the render. This should do what you're looking for:

class Flicker extends React.Component {
    constructor(props){
        super(props);
        this.state = {mode: "On"};
    }

    flipOn(){
        this.setState({mode: "On"})
    }

    flipOff(){
        this.setState({mode: "Off"})
    }

    render () {
        return (
            <button onClick={(this.state.mode === 'Off') ? this.flipOn : this.flipOff}>State: {this.state.mode}</button>
        )
    }
}

export default Flicker;

How to render a component on button click in React?, How do you render a component on a button click in react? The extended JavaScript comes when you look at the return value of the render method. This is very close to actual HTML, together with the JSX syntax for a CSS class. By looking at the JSX, you can get a feeling for React’s model for rendering. You tell React, what you expect from rendering a view. And this definition is valid at any point in

Put the conditional logic inside the render() method.

Something like this...

class Example extends React.Component {
  // the rest of your code

  render() {
     const { mode } = this.state;
          return(
              <div>
                 {mode ==="on" && <button onClick={this.flipOn}>State: On</button> }
                 {mode === "off" && <button onClick={this.flipOff}>State: Off</button>}
               </div>
          )
    }
}

What is the difference between render and return in reactjs?, What is the difference between render and return in react? Embedding Expressions in JSX. In the example below, we declare a variable called name and then use it inside JSX by wrapping it in curly braces: You can put any valid JavaScript expression inside the curly braces in JSX. For example, 2 + 2, user.firstName, or formatName (user) are all valid JavaScript expressions.

Your component changes the state. The state is boolean - either on (true) or not (false). Since you're state is switched between two value, you can use a single method (toggle). Since we check the previous state, it it's better to setState via updater.

You need to bind the method to this, by using bind in the constructor (method 4) or an arrow function via an instance method (method 5).

Now in the (single) render, you only need to change the text according to the state of on:

class Flicker extends React.Component{
  state = { on: true };

  toggle = () =>
    this.setState(({ on }) => ({ on: !on }));

  render() {
    const text = this.state.on ? 'On' : 'Off';

    return (
      <button onClick={this.toggle}>State: {text}</button>
    );
  }
}

ReactDOM.render(
  <Flicker />,
  demo
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="demo"></div>

Elements are the smallest building blocks of React apps. We call this a “root” DOM node because everything inside it will be managed by React DOM. given moment, rather than how to change it over time, eliminates a whole class of bugs. If you want to iterate over a list to render more than one component or implement some conditional logic, you have to use pure JavaScript. You don’t have a lot of options with looping, either. Most of the time, map will cover your needs.

Conditional rendering in React works the same way conditions work in render a part of the component while the rest of the output doesn't change. class LoginControl extends React. It can be handy for conditionally including an element: In the example below, we use it to conditionally render a small block of text. Comments in JSX are weird and when searching for information, it's hard to find a straightforward answer. So here it is: You can't just use HTML comments inside of JSX because it thinks they are real DOM Nodes: render {return (< div > <!-- This doesn't work! --> </ div >)}

All things being equal, always favor simplicity and readability — even when choosing which conditional rendering This tutorial covers the most popular conditional rendering methods: Let's start with the most naive implementation using an if/else block and build it from there. class App extends React. React uses a render method which you have seen above to hold component views. Component’s render method return JSX which then use to create real HTML output which will be rendered in the browser. The interesting Thing about render method is that it runs every time when your component State or Props updates. This process ensures whenever you

Here we have a single React component rendering a string: from "react-dom"; class App extends Component { render(){ return to be read-only, states are used for data that can change based on user In the same way a function might require mandatory arguments, Then i use this inside th return. It involves using a conditional inside of your JSX that looks like checkIfTrue && <span>display if true</span>. Because if statements that use && operands stop as soon as they find the first value that evaluates to false, it won't reach the right side (the JSX) if the left side of the equation evaluates to false.

Comments
  • flipOff never called in your code also without extending the React Component how does this class would work
  • Thanks - edited accordingly. @Dan, it's very flexible - basically your logic does belong in the render, but how you choose to do that is up to you. I believe that returning a different button based on the state is a little overkill. You can use the same button with different properties, but that's up to you.
  • So it would be: render>logic>return?
  • Thank you Filip, this is exactly what i needed to know!
  • @Flip I edited your answer. It won’t be good to use if else in render. Take a look at edited answer and let me know if you have any queries
  • What if the state rendered also renders text or a form or something else, and the state changing button? Does this also work for things such as that?
  • This is a button, a button should be simple. If you want something more complicated, create other simple components and compose them together. In this case, the button shouldn't have a state of it's own. In should get the on state via prop, and a callback to change the state of on in a parent. Now you can do whatever you want with the on value outside.
  • I've added a real world example of the Flicker in use.
  • The sample code I proposed initially is not about the button having a state of its own. A variable called mode has the value of the string "On" or the string "Off", which changes by pressing the button. So it is with the intention of it being as simple as possible. The button's only function, rather than turning on or off a state, is about rendering on or off a whole div element with more jsx elements inside.
  • This is the fundamental intention of the Flicker class. And it's just to resolve a doubt, that is why the sample of the idea is a simple on or off switch. Don't get me wrong though, what you propose is just as valid, although not towards what my question was appointed.