How to pass params from laravel to react.js?

Member

by mac , in category: PHP Frameworks , a year ago

How to pass params from laravel to react.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , a year ago

@mac 

There are several ways to pass parameters from Laravel to React.js:

  1. Using Blade templates: You can pass parameters from Laravel controller to Blade templates and then pass them as props to your React components.


Example in Blade template:

1
<div id="root" data-props="{{ json_encode($data) }}"></div>


Example in React component:

1
2
const data = document.getElementById('root').getAttribute('data-props');
ReactDOM.render(<App data={JSON.parse(data)} />, document.getElementById('root'));


  1. Using AJAX requests: You can make AJAX requests from your React components to fetch data from your Laravel backend.


Example in React component:

1
2
3
4
5
componentDidMount() {
  fetch('/api/data')
    .then(response => response.json())
    .then(data => this.setState({ data }));
}


  1. Using API routes: You can create API routes in your Laravel application to serve data to your React components.


Example in Laravel routes/web.php:

1
Route::get('/api/data', 'DataController@index');


Example in DataController.php:

1
2
3
4
public function index() {
  $data = // retrieve data from database or wherever
  return response()->json($data);
}


Example in React component:

1
2
3
4
5
componentDidMount() {
  fetch('/api/data')
    .then(response => response.json())
    .then(data => this.setState({ data }));
}


These are just some of the ways you can pass parameters from Laravel to React.js. Choose the method that best fits your needs and requirements.

Related Threads:

How to pass route params to vuex getter?
How to add header params to iframe in react.js?
How to get query params from url in react.js?
How to pass data into iframe in react.js?
How to pass props in the url in react.js?
How to pass `?` with url in laravel?