stackdave stackdave - 2 months ago 10
React JSX Question

Dependency Injection in Stateless function is ok, but how do it in normal React Component

I have a Stateless function like my main component, and I'm testing DI and works, but I can't resolve same for a normal component (look second block below). I'm adding myVar parameters to the component after print states with {...store.getState()}

Stateless: it's working, i can change the order in the parameters of function.

const TodoApp = ({
todos, // order variables , it's not important with DI
myVar, // order variables , it's not important with DI
visibilityFilter // order variables , it's not important with DI

}) => {
return (
<div> myVar: {myVar} // it's working
</div>
)
}
const render = () => {

ReactDOM.render(
// Render the TodoApp Component to the <div> with id 'root'
<TodoApp
{...store.getState()} myVar='value Var'
/>,
document.getElementById('root')

)
};

store.subscribe(render);
render();


Normal React Component ES6: how do Dependence Injection automatically without use props like in the block above ?

class TodoApp extends Component { // agregado export default
constructor( here ??? ) {

}


render() {
return (
<div> myVar: {this.myVar }
</div>
)
};
}

const render = () => {
console.log ( ...store.getState());
ReactDOM.render(
// Render the TodoApp Component to the <div> with id 'root'
<TodoApp
{...store.getState()} myVar='value Var'
/>,
document.getElementById('root')

)
};

store.subscribe(render);
render();

leo leo
Answer

Access the injected params with this.props

class Contacts extends React.Component {
  // You don't even need a constructor
  // constructor(props) {
  //  super(props);
  // }     

  render() {
    return (
      <div>Contacts: {this.props.myContact} </div>
    );
  }
}

See a working example here