Retrieving data from a script within a React component

How can I access a variable from a script inside a React component?

I am performing device detection on Node and sending the resulting object to the client (React) within index.ejs.

<script  type="text/javascript">window.deviceType = <%- deviceType %></script>

While I am able to console.log window.deviceType successfully inside the React component, attempting to use it results in an error stating "error, window is not defined."

.

For instance, within the React component:

    return(
      <div>
       <Menu.Item>
         {window.deviceType.isMobile ? (
            <Link to="/">
                <h1>React Boilerplate 23</h1>
            </Link>
         ) : (
                 <div>PROBLEM</div>
          )}
        </Menu.Item>
        <div type="button" onClick={() => console.log(window.deviceType)}>
          XX
        </div>
       </div>
     )

While I can easily console.log the variable, using it in logic as shown above causes rendering issues while still allowing for successful console logging.

The same issue arises when trying the following approach:

<script  type="text/javascript">var deviceType = <%- deviceType %></script>

Answer №1

window is always accessible in the browser, ensuring that the original code does not trigger a window is not defined error on the client side. This issue may only arise when a React application is being rendered on the server side.

The window.deviceType.isMobile ? expression is processed on the server side, while the onClick callback takes place on the client side to prevent any errors.

Assigning global.window = global in Node.js might not be suitable because the value is specific to the current request, rather than truly global.

A recommended method involves separating deviceType from window and providing a universal value for the application using React-specific techniques such as props, state, or context. The value can be passed down as a prop from the entry point, stored in the Redux store if necessary, or made globally available in the app through React context:

export const DeviceTypeContext = React.createContext();

...

<DeviceTypeContext.Consumer>
  {deviceType => (
   <Menu.Item>
     {window.deviceType.isMobile ? (...) : (
             <div>PROBLEM</div>
      )}
    </Menu.Item>
  )}
</DeviceTypeContext.Consumer>

For the client side:

render(
  <DeviceTypeContext.Provider value={window.deviceType}>
    <App />
  </DeviceTypeContext.Provider>,
  ...
);

For the server side:

renderToString(
  <DeviceTypeContext.Provider value={someVariable}>
    <App />
  </DeviceTypeContext.Provider>,
  ...
);

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

Reactjs rendering problem related to webpack

Greetings! I am new to using react js and decided to create a quiz application. However, I encountered an error when the render function was called. Below is my webpack.config file: module.exports = { entry: { app: './src/index.js' }, ...

What is the best way to update multiple records in mongoose?

Upon discovering the script below: Device.find(function(err, devices) { devices.forEach(function(device) { device.cid = ''; device.save(); }); }); I noticed that MongoDB offers a "multi" flag for updating multiple documents simultane ...

React- Struggling to modify state from child component using function declared within a parent component

This is my main component: import React, {useState} from 'react'; import SearchBar from '../components/SearchBar'; import WeatherDisplay from '../components/WeatherDisplay'; import LocationInfo from '../components/Locat ...

Issue with hook not updating when invoked inside useEffect

I'm encountering an issue with updating the state after fetching data from my API. The API response seems to be correct, but for some reason, my weatherData-hook is not getting updated and it returns undefined. Can anyone point out what mistake I migh ...

How to use jQuery with multiple selectors?

I am attempting to create a feature where multiple links are highlighted when one is clicked. However, I am encountering an issue where only the link that is clicked is being highlighted, rather than all three links. Below is the code snippet: $('#v ...

Tips on modifying the border, text color, and border color of Material-UI TextField when hovered over

I'm struggling to grasp the concept of customizing MaterialUI components. Although I have read through the documentation at https://material-ui.com/customization/components/ on how to customize using classes and className, I am still finding the advan ...

JavaScript - Need to automatically scroll to a different div when scrolling occurs

Currently, my focus is on creating a single-page website where the main content is displayed in large boxes arranged vertically down the page. If you have any suggestions or thoughts on using JavaScript to navigate to each content box more efficiently, I ...

What is the best way to make gulp-vulcanize exclude the socket.io.js file from processing?

One of my HTML files includes a reference to /socket.io/socket.io.js, and I want to vulcanize this file while ignoring that particular script tag. Here is the gulp task I created for this purpose: // Vulcanize HTML files var vulcanizeHtmlSrc = 'view ...

When trying to run the "npm start" command, I encountered a syntax error that specifically mentioned the use of

Every time I attempt to run the npm start command, I encounter the following error: I have followed the steps provided in this link: https://github.com/kriasoft/react-starter-kit/blob/master/docs/getting-started.md Could you please advise on how to resolve ...

Floating Action Button is not properly attached to its parent container

When developing my React Js app, I decided to utilize the impressive libraries of Material UI v4. One particular component I customized is a Floating Action Button (FAB). The FAB component, illustrated as the red box in the image below, needs to remain p ...

Semantic-ui-react cannot be located by Docker

I am a beginner when it comes to docker and I'm looking to create a React app, specifically using TypeScript, inside a docker container. In order to do this, I need to incorporate semantic-ui-react into my project. I followed the instructions provide ...

Tips for accessing Ajax data within Ember computed property

I'm facing a challenge with returning data from an Ajax call in a computed property. Despite being aware of the asynchronous nature, I am unable to figure out how to do it due to the specific requirement of returning the data in an array format with o ...

Best practices for updating the token in an Angular 2/5 application - tips on how, where, and when to refresh

Currently I am utilizing the following technologies: Django REST Framework Angular 5 RxJS + OAuth2 Within all components paths except LoginComponent, I have an AuthGuard to verify the token data stored in localstorage of the browser. If valid data is ...

How to iteratively process JSON array using JavaScript?

I am currently attempting to iterate through the JSON array provided below: { "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "<a href="/cdn-cgi/l/email-pro ...

Tips for stopping Vue.js automatic merging of CSS classes

Recently, I embarked on my journey with Vue.js and have been thoroughly enjoying the experience. However, I've stumbled upon a challenge that has me stumped. Despite searching high and low and studying the documentation, I haven't found a solutio ...

Implementing setInterval in ReactJS to create a countdown timer

I have been working on developing a timer application using React. The functionality involves initiating a setInterval timer when a user clicks a specific button. const [timer, setTimer] = useState(1500) // 25 minutes const [start, setStart] = useState( ...

The element type 'x' in JSX does not offer any construct or call signatures

I have recently imported an image and I am trying to use it within a function. The imported image is as follows: import Edit from 'src/assets/setting/advertising/edit.png'; This is the function in question: function getOptions(row) { ...

Update the main color in the Material UI theme on the fly

I have a requirement where users should be able to choose their primary color from a list containing options like Blue, Orange, and Green. I have implemented the latest Material UI for the front-end. Currently, I am able to switch between light and dark t ...

Encountering an Express.js HTTP 500 ERROR when using res.send("Some text"); is working on the page, however, the error occurs when trying to use res.render('file');

My website has a page located at /request that features a form. The form's method is POST and the action leads to /request. In the POST handler in request.js, the intention is to take action with the form data, like storing it in a database, and then ...

Instead of displaying a regular text box, the output unexpectedly shows "Printing [object HTML

There are some HTML and JavaScript files that I have. I've written some functions in my JavaScript file to save the values of different input fields. However, when I try to print the description, it just displays [object HTMLInputElement]. This mak ...