1

I need, when a user clicks on a button, that React renders a table under said button. How to do it?

let a = '';

if (this.state.text) {
  a =
    <table border="1" width="40%" cellpadding="5">
      <tr>
        <th>Ячейка 1</th>
        <th>Ячейка 2</th>
      </tr>
      <tr>
        <td>Ячейка 3</td>
        <td>Ячейка 4</td>
      </tr>
    </table>
} else {
  a = ''
}
1

1 Answer 1

1

Create a button within your component that has the onClick event listener. Then, adjust the state variable where you control the table rendering accordingly (in your case, the text state variable).

Finally, within the render function, conditionally render the table based on the state.

class App extends React.Component {
  constructor(props) {
    super(props)

    // State variables
    this.state = {
      // Controls table rendering
      text: true
    }
  }

  render() {
    return (
      <div>
        {/* Conditionally rendering table */}
        {
          this.state.text ? (
            <table>Table</table>
          ) : ''
        }

        {/* Button with onClick event listener */}
        <button onClick={() => this.setState((state) => {
          return { text: !state.text }
        })}>Button</button>
      </div>
    )
  }
}
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.