1

Working version

// Load from defined component
const TextField = require('textfield');

render: function() {
  <div>
   <TextField label='sample' defaultValue='default' placeholder='type your value' />
  </div>
}

Improved version, but not working

And then I have so many TextField, so I refactor my code to create the props in a more generic way. Then, I expect kind of things like this will work, but it won't:

render: function() {
  <div>
   // This not working but raised error: Objects are not valid as a React child (found: object with keys: {label, defaultValue, placeholder}
   React.createElement(TextField, this._getPropsForField('sample'))
  </div>
},

_getPropsForField: function(fieldName) {
  // Initialize data for fieldName, but return a mock for now
  return {
    label: 'sample',
    defaultValue: 'default',
    placeholder: 'placeholder'
  };
}

I also tried:

TextField(this._getPropsForField())

But it didn't work with the same error.

I appreciate any help or suggestion, thank you guys!

3 Answers 3

1

You can pass a whole set of props using the spread operator, which has a kind of special use case in JSX.

<TextField { ...(_getPropsForField('field')) } />

Example

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

1 Comment

Yes, ... does the magic! Any other options to make it work?
1

Going full JSX is better, but this line:

React.createElement(TextField, this._getPropsForField('sample'))

You are missing the { } brackets to escape JSX. With them it should work also:

{React.createElement(TextField, this._getPropsForField('sample'))}

2 Comments

Shouldn't this be rendered as a string instead of giving an error in the case the {}s are missing?
Yes it should. But the string would not raise the error :) I guess the original code that raised the error was different than in your question.
1

I don't know JSX much but I think you can't put React.createElement(TextField, {}) inside <div> (as @wintvelt points out, you have to wrap it inside a {}). So I would use pure JS like this:

render: function() {
  textField = React.createElement(TextField, this._getPropsForField('sample'));

  return React.createElement('div', null, textField);
  // Or this shortcut:
  return React.DOM.div(null, textField);
},

Or with pretty CoffeeScript:

render: ->
  React.DOM.div
    null
    React.createElement TextField, @_getPropsForField('sample')

1 Comment

If you put it in {} brackets, you can actually put it inside JSX. JSX code actually compiles to React.createElement().

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.