Implement React JS in Yii2

Hi, want to know that can we use yii2-react extension in a single module of an existing built project. My complete project is built in Yii2 but I want to prepare dashboard in React JS.

So anyone please tell me is it possible or not?

Hi, Okay what yii2-react does it just includes the js files for you it does not provide tools to auto generate the app or components, what you can do is download the js files yourself and put them in web/js and require them in your module layout file.

Thanks for the suggestion. Is it possible to call react component in Yii2 layout file for ex: In my dashboard side bar and header will be from yii2 layout but middle container will be of React Component.

If is possible then how can we do it? I have included js files in my view along with react component.

Index.js

import React from ‘react’;

import ReactDOM from ‘react-dom’;

ReactDOM.render(

<h1>Hello, world!</h1>,

document.getElementById(‘root’)

);

But it is now working, react js file is calling but did not rendering react html in yii2 view

you need a container which will contain your app for example you could have a div and mount your app in that div like so


<div id="react-app"></div>


ReactDOM.render(

  <h1>Hello, world!</h1>,

  document.getElementById('react-app')

);



Note: that dive could be anywhere provided you load the javascript after the div is created or loaded so include your javascript in the footer or put it in jquery dom load event

Thanks, it’s working if I inject react app build below the div, but not working If write down below code:

[color=#000088]<div[/color][color=#000000] [/color][color=#660066]id[/color][color=#666600]=[/color][color=#008800]"root"[color=#000088][font=arial, verdana, tahoma, sans-serif]></div>[/font][/color]

[/color][color=#000000]

<script> ReactDOM.render( <h1>Hello, world</h1> document.getElementById(‘root’)); </script>[/color]

I am getting an error "Uncaught SyntaxError: Unexpected token <" at the line "<h1>Hello, world</h1>

Because render accepts a string…

you are getting an error because ReactDOM.render expects a component as a first argument

Thanks All,

Now It’s working like as below:

<script type="text/javascript">

ReactDOM.render(

React.createElement(‘div’, null, ‘Hello World’),

document.getElementById(‘root’)

);

</script>