Nickon
Nickon

Reputation: 10156

Dynamic templates in React

I want to create a simple Wizard component that should be as generic as possible.

I want to inject 2 params for body content: template (with some logic included) and its context.

export class ParentClass extends React.Component {
    render() {
        let template = `Some text: {this.context.testFunc()}`;
        let context = new TestContext();

        return (
            <Wizard template={template} context={context} />
        );
    }
}

export class TestContext {
    testFunc() {
        return "another text";
    }
}

export class Wizard extends React.Component {
    context: null;

    constructor(props) {
        super(props);

        this.context = this.props.context;
    }

    render() {
        return (
            <div>
                {this.props.template}
            </div>
        );
    }
}

The problem is the logic included in template does not execute (it writes everything as a string in Wizard).

I use ES2015 and Babel for compiling.

Upvotes: 0

Views: 1835

Answers (1)

QoP
QoP

Reputation: 28397

When you are using template literals you have to use $.

For example

`Some text: {this.context.testFunc()}`; 

should be

`Some text: ${this.context.testFunc()}`;

Also, I think that you got a problem in your render function

render() {
        let template = `Some text: {this.context.testFunc()}`;
        let context = new TestContext();

        return (
            <Wizard template={template} context={context} />
        );
    }

should be

render() {
    let context = new TestContext();
    let template = `Some text: ${context.testFunc()}`;

    return (
        <Wizard template={template} context={context} />
    );
}

Hope it helps!

Upvotes: 2

Related Questions