CSRF Field in React (JSX)

Viewed 1062

In Laravel Blade, we access the CSRF field by putting @CSRF within a form. What I would like to do is to access the CSRF field in React JSX instead of Blade. I found an answer here React js - Laravel 5: Using csrf-token in POST method but I would like to know if there's a better way to do this.

How can I put a CSRF field in a form in (React) JSX in the best possible way?

1 Answers

The answer you mentioned is the preferred way to use csrf inside of react (i.e javascript). If I am right.

Although if you're using axios then you can add the token to axios globally.

//in your main layout file     
<meta name="csrf-token" content="{{ csrf_token() }}" />

If using axios for any request ( this must in the common script file of all pages )

// I am using jquery, you can do it in vanilla too 
axios.defaults.headers.common['X-CSRF-TOKEN'] = $(
  'meta[name="csrf-token"]'
).attr('content');

And for your csrf in jsx, if you have common js file for all your pages

Add in it : let csrfToken = $('meta[name="csrf-token"]').attr('content');

and in the form in JSX, use it this way

<input type="hidden" name="_token" value={csrfToken} />
Related