You can define code in a string and execute it in Javascript. We can use eval() to evaluate a String as a piece of code. This approach has a security, reliability, and performance concerns because eval can essentially inject code into your script, and that code is simply determined by what String is passed to it. That said, most Babel transpiling presets use strict mode, and this limits eval to some extent by ultimately not allowing it to instantiate new variables in the surrounding scope. What it can still do, is define a function and evaluate that function and assign it to a variable in the external scope like so:
var a = 5
var b = 10
var c = eval('function abc() { return a + b }; abc;')
assert(c() === 15)
With this ability in hand, we can wrap your entire 'renderCards' function definition in a String (by way of template literal):
export default `renderCards() {
let icon = this.state.icon;
....
....
....
}; renderCards;`
Import this string (import renderCardsImport from {relative path to file} in the react component MyFirstPage.js, and in the constructor you need to do a few things:
constructor(props){
super(props)
this.state = {
icon: // whatever this is
}
let renderCards = eval(renderCardsImport)
// so you have access to the parent class object this
this.renderCards = renderCards.bind(this)
}
And now you should be able to call renderCards() in the render() method or anyplace else in the component. Phewww. That was a doozy, but learned so much about eval, strict mode, etc. Hope it helps.
EDIT: You can also use the Function constructor it appears, as in var myFunct = Function('body of function with a return statement') but you will need to remember to bind it to this as well. If you use Function, you avoid performance and security hit of eval. Strict mode takes away most of the reliability problems.
let icon = this.state.icon;?export default class RenderCards extends Component { render = () => { // pass whatever was originally state as a prop now. }