18

How to create a reactjs component that will render the props data with another component. for example I have a sentence say "Hello guys this is {{name}}. How are you.". Now I want to replace the name with the reactjs component. when I try to replace the name with the component it shows as [object object].

First Edit:

var sentence = "Hello guys this is {{name}}. How are you.";

var tag_values = {'name': 'any Name'}

TagBox will take sentence and tag_value as props and replace the tags with the Tag component. and render it

var TagBox = React.createClass({
    render: function(){
        // replacing the tags with Tag component
        this.props.sentence = this.props.sentence.replace(tags_values['name'], <Tag \>)
        return(
            <div>
                {this.props.sentence} //Issue: This will Print as "Hello guys this is [Object Object]. How are you." 
                // But this should print as "This will Print as Hello guys this is any Name. How are you."
                // After clicking on "any Name" it should be replaced with input.
            </div>
        );
    }
})

Tag Component will replace the tag with input box on double click. and again replace input box with data on enter. This can be done using state.

var Tag = React.createClass({})
3
  • Can you give some example code? I don't understand why you need a React component to work with strings. Commented Jun 23, 2014 at 7:15
  • I am creating a page where user will be provided with a sentence say "Hello guys this is {{name}}. How are you." now when the user will click name he/she will get a input box to enter a name when the name is entered it will be displayed instead of {{name}}. now for every such tags I am creating Tag component which will be add to sentence by tagBox component. and the sentence string can very every time Commented Jun 23, 2014 at 16:43
  • Oh I see, that's a better description. Can you add some example code to your question so someone can help? In a gist: the value of the input box should be stored in state somewhere, and when the <input> is hidden it should be replaced with the value stored in `state. Commented Jun 23, 2014 at 16:53

4 Answers 4

17

Okay, so assuming that's a string you have as input, you need to create an array.

var parts = str.split(/\{\{|\}\}/g); 
// => ["Hello guys this is ", "name", ". How are you."]

The odd items are literal strings, and the even parts are the stuff between the brackets.

Now we'll create a helper function called mapAlternate. Which takes a function to call for odd elements, and a function to call for even elements in our array.

function mapAlternate(array, fn1, fn2, thisArg) {
  var fn = fn1, output = [];
  for (var i=0; i<array.length; i++){
    output[i] = fn.call(thisArg, array[i], i, array);
    // toggle between the two functions
    fn = fn === fn1 ? fn2 : fn1;
  }
  return output;
}

Now we can do something like this in our component:

render: function(){
    var parts = str.split(/\{\{|\}\}/g);


    // render the values in <strong> tags
    var children = mapAlternate(parts, 
        function(x){ return <span>{x}</span>; }, 
        function(x){ return <strong>{x}</strong> });

   return <div>{children}</div>;
}

Which gives us: "Hello guys this is name. How are you."

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

1 Comment

Thanks.. i was messing around and you made it to easy for me.
4

Have you heard of React String Replace ?

Here is a stateless component example:

import replace from 'react-string-replace';
const reg = /\{([a-z|A-Z|0-9|\.]+)\}/g;


const OutputComponent = props => {
    var str = 'Hello {name}, this is a "Super" component: {Super}';
    var output = replace(str, reg, prop => props.replacements[prop]);

    return <div>{output}</div>;
}

// later
import Super from './Super.jsx';
const obj = {
    Super: <Super />,
    name: 'John'
}

return <OutputComponent replacements={obj} />;

Comments

1

I just fixed this issue with react-jsx-parser

Your Example would be:

import JsxParser from 'react-jsx-parser'

export default class TagBox extends React.Component {
    render() {
       const sentence = "Hello guys this is <Tag>name</Tag>. How are you." // simply include the component in your string
        return(
            <JsxParser components={{ Tag }} jsx={ sentence } /> // identify the component in your string to inject
        )
    }
}

Comments

0

Nothing from above doesn't worked for me unfortunately. Here is a useful stable solution regexify-string (npm)

npm install --save regexify-string

Works like a charm

regexifyString({
        pattern: /\[.*?\]/gim,
        decorator: (match, index) => {
            return (
                <Link
                    to={SOME_ROUTE}
                    onClick={onClick}
                >
                    {match}
                </Link>
            );
        },
        input: 'Some initial string with [link]',
    });

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.