RaphaMex
RaphaMex

Reputation: 2839

How to inject a list of attributes as a string in ReactJS

I am writing a React component that makes my text editable. When clicked, it renders an input, when blurred it renders a text like before.

To make it work, I have to put a lot of attributes in my elements. I want to handle many types of inputs (text, number, date, textarea, ...) and I don't want to repeat this list all along.

Is there a way of writing this list only once and inject it in my elements?

Something like this:

const options = "value={this.props.value} placeholder={this.props.placeholder} onChange={this.props.onChange}  onBlur={this.stopEdit} ref={(e) => {this.eRef = e;}}";

Later used like that:

render() {
    return (<input type="text" {{options}} />);
}

I have read about dangerouslySetInnerHTML but that's not doing what I need.

Many thanks for your help!

Upvotes: 0

Views: 32

Answers (2)

Giang Le
Giang Le

Reputation: 7044

Why you dont use like this

const options = {
  value: this.props.value,
  placeholder: this.props.placeholder,
  ...
}

and html = <input type="text" {...options}/>

or you can use

html = React.createElement('input', {type: 'text', ...options})

Upvotes: 2

baeyun
baeyun

Reputation: 228

If you're looking on how to make text in your element editable, perhaps attach the content-editable="true" attribute to the element.

Hope this helps!

Upvotes: 0

Related Questions