The dependency injection (di) paradigm with 3rd party libraries in Aurelia

By : bsrdjan
Source: Stackoverflow.com
Question!

I am trying to create Aurelia custom element using React, by following this example on Aurelia Q & A and following exception occurs:

Potentially unhandled rejection [1] TypeError: Cannot read property 'render' of undefined

What I am doing wrong? Here my test code:

test.html

<import from="./myelement"></import>
<my-element foo.bind="Value"></my-element>

myelement.html

<template>
  <input type="text" placeholder="user">
</template>

myelement.js

import {Behavior} from 'aurelia-framework';
import {React} from 'aurelia-framework';

export class MyElement {
  static metadata(){
    return Behavior
      .customElement('my-element')
      .withProperty('foo')
      .noView();
  }

  static inject() {
    return [Element];
  }

  constructor(element) {
    this.element = element;
    console.log('this:', this);
    console.log('element:', element);
  }

  bind() {
    // React.render(<MyReactElement foo={this.foo} />, this.element);
    React.render(React.createElement(MyReactElement, { foo: this.foo }), this.element);
  }

  fooChanged() {
    this.bind();
  }
}
By : bsrdjan


Answers

The trick with importing third party libraries is you must choose how you wish to get access to the library. In your case if you are trying to create a single custom element using react that combines a view and a view model you can do so simply like this -

jspm install react

and then inside your view model -

import react from 'react'

Then you can use it anywhere in your view model, such as -

attached(element){
  // React pseudo-code
  react.render(element);
}

If you choose to load the library through dependency injection so that it is available as a module anywhere you have more options, but I think this should give you a start.

By : PW Kad


This video can help you solving your question :)
By: admin