1

I have custom component in which i map attributes. In this component I have label which have css class assigned. But i also want optional inline style for this label. The problem is that in react I need to surround inline style with curly braces and i can't escape them or set them correctly in component. How to resolve this?

Code from component:

const CustomComponent = ({items, name}) => (
    <fieldset>
        {items
            .map((item, index) => ({item, id: `${name || 'dod'}-${item.value || index}`}))
            .map(({item, id}) =>
                <div key={id}
                     className="className1">
                    <input
                        id={id}
                        name={name}
                        type="text"
                    />
                    <label htmlFor={id} className="className" style={item.style}>
                        {item.label}
                    </label>
                </div>
            )}
    </fieldset>
);

Code from rendered .jsx

  <CustomComponent             
       name="name"
       items={[{
           value: 'value',
           label: 'label',
           style: {{display: 'inline'}}      -> not working
       }]}
  />
1
  • Can you show us more code ? what is the type of item.style ? It must be an object literal ? if you are mapping, use key. Commented Feb 22, 2017 at 8:47

4 Answers 4

1

You only need to include the first {} when you are directly inside a Virutal DOM Object. <... items={object} .../> and then object should be written exactly the same way as other Object Literals. That being said you need {display: 'inline'} instead of {{display: 'inline'}} in

<CustomComponent             
   name="name"
   items={[{
       value: 'value',
       label: 'label',
       style: {{display: 'inline'}}      -> not working //use {display: 'inline'}
   }]}
/>

I've made a pen for this in Codepen, you can check it Here.

Sign up to request clarification or add additional context in comments.

1 Comment

Glad to be of use.
1

Your style property have to be an object literal, something like so :

item.style = {
 display: 'inline'
}

Comments

1

In react you can define your styles in form of JS objects, something like

  style: {{display: 'inline'}}

Comments

0

You can abstract this further and have a JS file holding all the styles for your page:

const styles = {
  myElement: {
    display: 'inline'
  }
}

then in the code...

<Component style={styles.myElement} />

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.