Did you get rid of this by mistake?
if (document.getElementById('root')) {
ReactDOM.render(<Main />, document.getElementById('root'));
}
https://code.tutsplus.com/tutorials/build-a-react-app-with-laravel-backend-part-2-react--cms-29443
The sample code in tutsplus link above works for me only if my welcome.blade.php is:
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel React application</title>
<link href="{{mix('css/app.css')}}" rel="stylesheet" type="text/css">
</head>
<body>
<h2 style="text-align: center"> Laravel and React application </h2>
<div id="root"></div>
<script src="{{mix('js/app.js')}}" ></script>
</body>
</html>
and my Main.js is
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
/* An example React component */
class Main extends Component {
render() {
return (
<div>
<h3>All Products</h3>
</div>
);
}
}
export default Main;
/* The if statement is required so as to Render the component on pages that have a div with an ID of "root";
*/
if (document.getElementById('root')) {
ReactDOM.render(<Main />, document.getElementById('root'));
}
...both as shown 2/5 of the way down on the tutsplus tutorial.
The problems for me begin if I go past those, into the Developing the React Application part of that tutorial. If I rewrite my Main.js file like it is there:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
/* Main Component */
class Main extends Component {
constructor() {
super();
//Initialize the state in the constructor
this.state = {
products: [],
}
}
/*componentDidMount() is a lifecycle method
* that gets called after the component is rendered
*/
componentDidMount() {
/* fetch API in action */
fetch('/api/products')
.then(response => {
return response.json();
})
.then(products => {
//Fetched product is stored in the state
this.setState({ products });
});
}
renderProducts() {
return this.state.products.map(product => {
return (
/* When using list you need to specify a key
* attribute that is unique for each list item
*/
<li key={product.id} >
{ product.title }
</li>
);
})
}
render() {
/* Some css code has been removed for brevity */
return (
<div>
<ul>
{ this.renderProducts() }
</ul>
</div>
);
}
}
If I open that in a browser, I only see the "Laravel and React application" but no "All Products."
Please or to participate in this conversation.