1

I have a state variable which stores JSX code that will be rendered to the DOM in the render() method. Here is the structure of state and the state variable jsxComp that I currently have,

state = {
    isLoggedin: false,
    jsxComp: null
}

What I am trying to do is I am trying to append JSX code ( a div ) into this variable inside a for loop as follows,

for(let i=0; i<postCount; i++){
    this.setState({
        //Append a div to the jsxComp variable
     })
}

How can I do that? + operator does not seem to work in this case.

Mehdi
  • 717
  • 1
  • 7
  • 21
  • 10
    normally you would not put JSX elements in the state. You put the data object in the state. Then in render you can apply the data to the JSX elements – Jackson Feb 26 '20 at 16:12
  • @Jackson Thanks for letting me know about this. So will how will the append be done? Using the `+` operator? – user12967133 Feb 26 '20 at 16:15
  • @user12967133 You can't append markup to an existing element. This is because jsx is actually not just text but an embedded language that will be transpiled to a function call. You basically ask how to append markup to the result of that function call which is an object rather than text. – trixn Feb 26 '20 at 16:32
  • This link might help you https://stackoverflow.com/questions/23616226/insert-html-with-react-variable-statements-jsx. – VipinKundal Feb 26 '20 at 16:44

1 Answers1

2

Never store actual elements in state. State should only contain the pure data to render, not the actual markup. Instead make your render() method conditionally render based on the state:

class MyComp extends React.Component {
  state = {
    isLoggedIn: false,
  };

  render() {
    const {isLoggedIn} = this.state;

    return (
      <div>
        {/* conditionally render based on isLoggedIn */}
        <p>{isLoggedIn ? 'You are logged in' : 'Please log in.'}</p>
        <button onClick={() => this.setState({isLoggedIn: true})}>
          Log In
        </button>
      </div>
    );
  }
}

Your render() method will be called whenever the state changes. React will then diff the result of the render and update the DOM where elements changed.

You also should not call setState() in a loop. First collect the changes and then call setState with the whole changed array. To actually append something to an existing array in state you would do:

this.setState(state => {jsxComp : [...state.jsxComp, newElement]});
trixn
  • 15,761
  • 2
  • 38
  • 55
  • Thanks for the info. But my question still remains unsolved. How will I append HTML code to JSX variables? – user12967133 Feb 26 '20 at 16:19
  • @user12967133 You can't do that. react is declarative. It works by defining what should be rendered given a certain state. You do not modify the markup in place. React does that for you. – trixn Feb 26 '20 at 16:34