1

Using react, I often find myself doing stuff like:

render() {
  var a, b, c = ...
  return <SomeClass a={a} b={b} c={c}/>
}

I tried doing <SomeClass a b c/> but it doesn't assign the properties to the component. Is there a more concise way of doing this?

4 Answers 4

2

You can try use Object(you can use new ES2015 feature called Object Literal Property Value Shorthand in order to avoid { a: a, b: b, c: c }) and spread attributes, like so

const a = 1, b = 2, c = 3;
return <SomeClass {...{ a, b, c } } />

Example

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

Comments

1

You can make use of the {... ext} syntax of ES6.

For example, you can get the same result as in your example by doing:

render() {
  var props = { a: ..., b: ..., c: ... }
  return <SomeClass {...props}/>
}

Comments

1

You can combine JSX spread attributes with ES6 object literal shorthand property initialization:

<SomeClass {...{a, b, c}} />

Comments

0

Well those were some quick answers, but yes as everyone's mentioned, the spread attribute in ES6 is commonly used to accomplish this:

var props = { a: 'Jim', b: 'Bob', c: 'Bill' };
return <MyComponent {...props} />

It's also useful to know that the order you define your props on the component is important, and can often be used to do loose conditional work, later props will override previous ones, so you can do things like:

var props = { a: 'Jim', b: 'Bob', c: 'Bill' };

return <MyComponent {...props} a={"James"} /> //Override 'Jim' with 'James'

Or:

var option = { a: 'Jim', b: 'Bob', c: 'Bill' };

return <MyComponent c={"William"} d={"Henry"} {...props} />

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.