Guide on rendering a component in React jsx using innerHTML

In my current project, I am developing a feature that allows users to toggle between graph and list views. The view's container is assigned the class name "two".

  toggleGraphView() {
    const two = document.getElementsByClassName('two')[0];
    two.innerHTML = '<span>Graph View!</span>'
  }

  toggleListView() {
    const two = document.getElementsByClassName('two')[0];
    two.innerHTML = "<ShotLog shotLog={this.state.shotLog}/>"
  }

When switching to the graph view text ('Graph View!'), everything works as expected. However, when trying to switch back to the list view, I encounter an issue. After executing toggleListView, the content of the 'two' container in Chrome tools shows

<shotlog shotlog="{this.state.shotLog}/"></shotlog>
. It should actually display
<ShotLog shotLog={this.state.shotLog}/>
to correctly pass the props.

I am unsure where the additional quotations are originating from. Do you have any insights?

Answer №1

Creating React components by embedding them in strings is not the recommended approach. Utilizing JSX, you can simplify your code as shown below:

this.state.showGraph ? <span>Graph View!</span> : <ShotLog shotLog={this.state.shotLog} />

By using a ternary condition, you can dynamically decide what content to render based on the value of a variable, showGraph.

The value of showGraph is stored in the component's state, which can be accessed using this.state. When you need to update the state of a component, you should invoke setState to trigger a re-render and display the desired content.

Here is a functional example:

class ShotLog extends React.Component {
  render() {
    return <div>Hi I'm a ShotLog</div>
  }
}

class App extends React.Component {
  constructor(props){
    super(props)
    this.state = { showGraph: true }
  }
  handleClick = ev => {
    this.setState({ showGraph: !this.state.showGraph })
  }
  render() {
    return (
      <div>
        {this.state.showGraph ? 
          <span>Graph View!</span> 
          : 
          <ShotLog />}
        <button onClick={this.handleClick}>Switch me !</button>
      </div>
    )
  }
}
    
ReactDOM.render(
  <App/>,
  document.getElementById('react')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>
<div id="react"></div>

If you want to learn more about JSX fundamentals, refer to the official documentation: https://reactjs.org/docs/introducing-jsx.html

For further insights on managing component state, check out this resource: https://reactjs.org/docs/state-and-lifecycle.html

Answer №2

While I may not be an expert in ReactJS, I believe the best approach is to return the correct content rather than manipulating it with JS:

  toggleView() {
      if (this.isGraphView()) {
          return <span>Graph View!</span>;
      } else {
          return <ShotLog shotLog={this.state.shotLog}/>
      }
  }

Answer №3

Building on @Justinas's response, you may consider implementing a conditional render instead of relying solely on raw JS. Here's an example:

class MyComponent extends React.Component {
  constructor(props) {
      super(props);
      this.state = {currView: 'graph'};
  }

  handleToggle() {
      if (this.state.currView === 'graph') {
          this.setState({currView: 'otherView'});
      } else {
          this.setState({currView: 'graph'});
      }
  }

  render() {
      if(this.state.currView === 'graph') {
          // render your 'graph' view
      } else {
          // render another view
      }
   }
}

Any changes to the component's state trigger a re-render, effectively replacing the previous content. Just ensure there's a mechanism to toggle or update the state :)

P.S. Apologies for any errors in the react syntax. No IDE at the moment!

Answer №4

If you want to avoid directly accessing the DOM using document.getElementsByClassName, you can leverage the React approach to toggle the view. Take a look at the example I've provided below.

class ToggleComponent 
{

constructor(props) {
  super(props); 
  this.state = {
    view: 'list', 
    data: someVal
  }

  toggleView() {
     const updatedView = this.state.view === 'graph' ? 'list' : 'graph'; 
     this.setState(() => {
      return {view: updatedView}; 
     });

  }

}


render() {
     const {view, data} = this.state;
     <div> 
       <button onClick={this.toggleView}> Toggle </button> 

       {view === 'graph'} && <span> Graph View! </span> 
       {view === 'list'} && <DataComponent data={data} /> 


     </div>
}



}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Angular: Importing Scripts in index.html and Implementing Them in Components

Currently, I am attempting to integrate the Spotify SDK into an Angular application. While I have successfully imported the script from the CDN in index.html, I am encountering difficulties in utilizing it at the component level. It seems like there may be ...

Can express middleware be tailored for each individual handler within the same route path?

I am seeking to create distinct routes under an /api path with varying middleware handlers, each allowing for different authentication methods. My initial approach was to nest these API routes under separate instances of the Router object using Express: c ...

Tips on accessing close autoComplete/TextField title in AppBar

Looking to add a search bar and login button in the AppBar, where the search Bar is positioned close to the title. The desired order for the AppBar components should be as follows: Title SearchBox LoginButton How can this be achieved? Below is th ...

What is the best way to dynamically showcase options in a React application?

product.js Qty: <select value={qty} onChange={(e) => { setQty(e.target.value) }}> {[...Array(product.countInStock).keys()].map((x) => ( <option key={x + 1} value={x + 1}> ===> I need to dynamically display options b ...

How to access class type arguments within a static method in Typescript: A clever solution

An issue has arisen due to the code below "Static members cannot reference class type parameters." This problem originates from the following snippet of code abstract class Resource<T> { /* static methods */ public static list: T[] = []; ...

What steps can you take to ensure that a single-page-application (SPA) is easily searchable within a SharePoint environment

In the process of developing a single-page-application (SPA) with ASP.NET MVC, knouckout, and various other libraries, we have decided to handle routing on the front-end, potentially utilizing crossroads.js. Our use of slickgrid.js allows us to present a w ...

Is it possible to utilize non-pure objects as state in React?

I am considering using a function instance as the state object in React instead of a pure object. However, I'm unsure if this approach is acceptable: class Test extends Component { constructor(props) { super(props); this.state = new Domain( ...

What are some ways to streamline this D3 script?

My CSV data displays pass rates by organisation for different years: org,org_cat,2004_passed,2004_total,2005_passed,2005_total,2006_passed,2006_total GSK,industry,35,100,45,100,55,100 I am using D3 and aiming to create a dictionary of organisations struc ...

Attempting to serialize a form using Ajax and jQuery

I am facing an issue with submitting user input from a modal using jQuery and AJAX. The problem is that the AJAX call is not capturing the user input. Even though the AJAX call is successful, when I check on the server side, the user input appears to be bl ...

creating a fresh window using AJAX in Ext JS

While I know there may be similar questions out there, the details of my situation are unique. I'm facing an issue with building a new window using ExtJS, starting from a pre-existing grid. The goal is to populate this new window with references to el ...

VueJS Error: Unable to access the 'className' property of an undefined variable

I'm currently working on a menu design project where I need to highlight the active tab/page that the user is on by adding a color class and utilizing JavaScript to update the active link. Here's a snippet of my template: <div class="menu ...

Show the message "No results found" if there are no matches, or hide the DIV displaying search results using AJAX and MySQL

I'm struggling with getting my search bar to display "No matches found" or hide the results div completely when a query doesn’t match any “Name” in the MySQL database. The search bar works for displaying AJAX live search results using MySQL, PHP ...

Strange issue: the code appears to be running multiple times with just one click

I've implemented a commenting system with a like feature. However, I'm facing an issue where sometimes clicking the like link results in sending multiple requests (up to 8-9) per click. This problem also occurs with another jQuery code that is tr ...

Exploring the functionality of arrays within Selenium IDE

Recently delving into Selenium IDE, I am a beginner and looking for guidance. The challenge at hand: How can I access values from an array generated by execute script | var array1 = document.getElementsByClassName("Post"); return array1; | array1 Initi ...

Achieving dynamic population of a second dropdown menu based on selection from the first dropdown menu using PHP

In my current project, I am faced with the task of populating three different menus. The first menu is generated using a MySQL query in PHP and displays TV shows like "Modern Family" or "Dexter". What I want to achieve is that once a TV show is selected fr ...

Is there a way to iterate through indexed variables in javascript?

After receiving an array of data from a JQuery .ajax function, I noticed that the fields in the array are named and numbered like part1, part2, part3, etc. I attempted to loop through this data using the code below, but unfortunately, it resulted in NaN: ...

Move the JavaScript code from the <script> element in the HTML file to a

Recently, I've been exploring the idea of incorporating a tradingview ticker on my website. Trading view has kindly provided me with a snippet to embed into my webpage: <!-- TradingView Widget BEGIN --> <div class="tradingview-widget-co ...

eliminate item from list upon user clicking the button

Does anyone have any tips on how to effectively store and remove user-selected items from an object in JavaScript? I'm encountering an issue where only the first object in the array is being removed, and not the others. Any help would be appreciated! ...

Gathering the output from every function within an array of functions

I've searched extensively for a solution to this dilemma, but have had no luck so far. Therefore, I am turning to the community for help. Please feel free to direct me to any existing similar queries. My challenge involves working with an array of fu ...

Is there a way to prevent pixels from being rendered outside of a designated rectangle in HTML5?

I'm looking to add screen-in-screen functionality to my HTML5 game, and I have an idea for how to approach it: //Function called every frame function draw(){ set a mask rectangle only draw pixels from the current frame that fall within this recta ...