React - method for transmitting dynamically generated styles to a div element

As a newcomer to the world of React, I keep encountering an unexpected token error related to the ":". Can someone please assist me with understanding the correct syntax for including multiple styles within the Box component provided below? Additionally, how can I create an array of Box components, each styled differently in terms of margin, and then display them on a webpage?

ncaught SyntaxError: /Inline Babel script: Unexpected token, expected "}" (51:73)

const Box = (props) => <div style={"margin-left" : props.spacing, "width" : props.width, "height" : props.height, "background-color" : props.color}></div>
     |                                                                          
                                                 ^

The Box component accepts various properties such as margin-left (which I'm not sure if it's valid in React). My intention is to use a for loop to populate an array with different Box components, each with a unique margin value, resulting in a row of distinct elements inside a div.

class StoryPage extends React.Component {
      render(){
         const Box = (props) => <div style={"margin-left" : props.spacing; "width" : props.width; "height" : props.height; "background-color" : props.color;}></div>
         const val = 0
         const boxArray = []
         for(let i = 0; i < 10; i++){
             val += 100
            boxArray.push(<Box spacing={val} width="100px" height="100px" color="black" />)
         }
         return(
              <div>
                {boxArray}
              </div>
         )
     }
 }

I hope to see an array of Box elements displayed on the page, but I'm unsure about the correct implementation for achieving this.

Answer №1

You’re making a mistake in your syntax for passing an object literal as a prop — keep reading for an explanation.


When passing React props, use the following methods:

  • string literal

    <Component strProp='hello' />
    // or
    <Component strProp={'hello'} />
    
  • variable

    <Component strProp={this.props.foo} />
    
  • array literal

    <Component arrProp={[1, 2, 3]} />
    
  • object literal

    <Component objProp={{foo: 'bar'}} />
    

Notice the double curly brackets? One pair is required to enclose any non-string-literal expression passed as a prop, while the other is part of the object literal notation.


On the contrary, the following example is incorrect:

<Component objProp={foo: 'bar'} /> // <- WRONG

This would not work because foo: 'bar' is not considered an expression.

Answer №2

Hugo is correct. It's important to note that adding larger margin-left values to each element will determine the distance from the border to the left of the element. Check out this link for more information on the CSS box model: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model

If you set the display property to "inline" on all your divs, it will change the layout of divs from block to inline. Alternatively, if you don't make any changes, they will still be displayed. For further details, visit: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flow_Layout

Answer №3

One issue lies within this line of code:

const Box = (props) => <div style={"margin-left" : props.spacing; "width" : props.width; "height" : props.height; "background-color" : props.color;}></div>

The problem is with the way you are providing the style attribute. It should be structured like this:

const Box = (props) => (
  <div 
    style={{
      marginLeft: props.spacing, 
      width: props.width, 
      height: props.height, 
      backgroundColor: props.color
    }}
  />
);

Remember to use double curly braces for the style attribute and separate properties with a comma ,

Check out the demo here

Note: When using inline styles in React, make sure to follow camelCase naming convention.

For instance,

  • margin-left should be marginLeft.
  • background-color should be backgroundColor.

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

Variability in Swagger parameter declaration

Is it possible to specify input parameters in Swagger with multiple types? For example: Consider an API that addresses resources using the URL http://localhost/tasks/{taskId}. However, each task contains both an integer ID and a string UUID. I would like ...

Attempting to cycle through rows of a table and triggering setInterval for each row does not appear to be successful

I am attempting to change the value of a cell from Offline to Online (and vice versa) within my DataTable by utilizing a web service. var $myTable = $("#my-table").dataTable(); var $myTableRows = $myTable.fnGetNodes(); for(var i=0; i<$myTableRows.leng ...

"Utilizing a hidden overflow combined with border-radius and translate3d for a

Is there a way to keep the corners of a block hidden when it has both overflow set to hidden and border radius applied while being translated? HTML <div class="scroller"> <div class="scroller-content"></div> </div> CSS .s ...

When a React CSS class is deployed to a production server, it may be automatically

I've encountered a strange CSS issue while working on my React project. One specific section of the JSX <div> has a class with style properties defined in the main .css file. During local development, everything appears as expected. However, aft ...

Using Node.js with Express to seamlessly pass objects to EJS templates

I have a scenario where I am passing an object to my template and I want to display the details of that object in HTML. app.get('/', function (req, res) { var user = req.session.passport.user; if ( user != 'undefined' ){ ...

Send the user back to the homepage without the need to refresh the page

When the user clicks "Okay" in my window.prompt, the code below opens a new tab. Is there a way to direct the user to the home page without opening a new tab? if (window.confirm("Do you really want to leave?")) { window.open("./Tutoria ...

Is it possible to implement ajax within an onclick function using React?

Is there a way to implement ajax in an onclick function while working with React and display the results within that function? onItemClick(a) { console.log("Button was clicked!"); var desc = Flightdesc.info.departureinformation.routeshow.description ...

What are the steps to troubleshoot and fix the Internal Server Error on Next.Js?

I recently set up a new Next.js app using the command npx create-next-app. After that, I added Sass to my project with yarn add sass and proceeded to run it with yarn dev. To my surprise, I encountered multiple errors in both my terminal and on localhost. ...

Is a Selenium loop a viable option?

</head> <body> <table cellpadding="1" cellspacing="1" border="1"> <thead> <tr><td rowspan="1" colspan="3">test</td></tr> </thead><tbody> <tr> <td>click& ...

Having issues with nth-child? It seems like nth-of-type isn't working either

I am trying to change the color of all even titles from h2 to orange using nth-child. However, I seem to have made a mistake somewhere and can't figure out what it is... *{ font-size: 1em; } h2{ font-size: 1.5em } ...

Utilize a jQuery selector to target the initial element of every alphabet character

I'm seeking some assistance with jQuery selectors and have a specific scenario that I need help with. Here is the HTML structure I am working with: <ul> <li class="ln-a"></li> <li class="ln-b"></li> <li cl ...

Tips for making a scrollable container that allows its contents to overflow without clipping?

Currently working on implementing a horizontal card row for my website with a unique hover effect - the cards lightly rotate and raise on hover. Here is a preview: https://i.sstatic.net/eDQ59.gif To make this row responsive, I added overflow-x: auto; to e ...

Dynamic JavaScript Total Calculation

I have been struggling to update the total price for specific options. Even though the code was created by someone else and has worked fine for many users, I can't seem to make it work correctly. Any assistance would be greatly appreciated. Here is t ...

Looking for Protractor CSS functionalities nodes

I tried the code below but am having trouble locating the "Login" text using Protractor: <div _ngcontent-c2="" class="align-center"> <img _ngcontent-c2="" alt="Autoprax" class="ap-logo" src="/images/apLogoSmall.svg" style="width: 100%"> ...

What steps can be taken to remove a server-side validation error message once the user has inputted the correct value?

I'm facing an issue with server-side validation messages on my form, which includes fields for Name, Mobile, Email, and Message. While JQuery validation works fine, clearing the error message after user input is causing a problem. Using AJAX to submi ...

Encountering an issue with HTMLInputElement when trying to input an integer value into a label using JavaScript

script code intext = document.getElementById("intext"); totalin = document.getElementById("totalin"); function myFunction() { var x = document.getElementById("totalin"); x.innerHTML = intext.toString(); } The snippet above shows a JavaScript functio ...

Utilizing CSS to incorporate a background image into HTML code

Is it feasible to utilize pure HTML for the background-image property? Consider the following scenario: The original: background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height=&apo ...

inject the HTML content into the <div> container

Snippet: https://jsfiddle.net/x9ghz1ko/ (Includes notes.) In my HTML file, there are two distinct sections: <section class="desktop_only"> and <section class="mobile_only">. The challenge lies in positioning a JavaScript sc ...

Error: Unable to access the 'resource' property as it is undefined

I am currently working on a project that involves fetching the latest 4 results from Craigslist using a query. Although I have successfully retrieved all the relevant information, I seem to be encountering an issue with loading the URL of the image from th ...

The useForm function from react-hook-form is triggered each time a page is routed in Nextjs

Hey there, I'm just starting out with Next.js (v14) and I'm trying to create a multi-page form using react-hook-form. But I'm encountering an issue where the useForm function is being executed every time, and the defaultValues are being set ...