moving from twig to ReactJS: how to extend a template/component to build full reactJS pages? implement react-router and redux into symfony?
Take a look at this fiddle, with react-router
you can separate each page and create components, layouts and views.
ReactDOM.render( <Router> <Route path="/" component={AppContainer}> <IndexRoute component={HomeView} /> <Route path="list" component={ListView} /> </Route> </Router>, document.getElementById('root'));
Create two views, home
and list
, they may look like this:
class HomeView extends Component { render() { return ( <MainLayout sidebarTitle="Links" sidebar={<SidebarList />}> Hello world! This is the HomeView! </MainLayout> ); }}
Inside each view extends
from a layout and pass the properties like what component we need to be a sidebar
and a children
.
class ListView extends Component { render() { return ( <MainLayout sidebarTitle="Text" sidebar={<SidebarText />}> <h1>List</h1> <ul> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> </ul> </MainLayout> ); }}
In the layout use that properties to display the content in as you do with twig.
class MainLayout extends Component { render() { return ( <div> <Navbar title="APP" /> <div> <div> {this.props.children} </div> <div> {this.props.sidebar} </div> </div> ); }}
Maybe it's a little bit confusing but you need to take a look at the fiddle, it's the closer I can do based on your example.
I suggest you start small to get the hang of how ReactJS works. You can easily use ReactJS for only a limited portion of your app.
Let's say you want to change a component of your app that sits inside a div with id "myComponent". You can put a script on your page that makes this into a ReactJS component (ES6 syntax):
import MyComponent from './mycomponent';ReactDOM.render( <MyComponent />, document.getElementById('myComponent'));
In this code, <MyComponent />
signifies your main React Component in the mycomponent.js file in the same folder. For one small component, you won't need Redux stores; simply store all state in the component's this.state
. When adding more components that re-use the same state, Redux is a very nice way to go about this.
Note that you will need some extra setup to get the simple example to work. <MyComponent />
is JSX, not plain Javascript. You need a transpiler like Babel to convert this into plain js (and as a bonus, it also supports ES6 notations). Also, don't forget to include React and React-Dom!