2

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
  • use api.php it req. token and not req. csrf token Commented Jan 27, 2021 at 7:18

1 Answer 1

4

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} />
Sign up to request clarification or add additional context in comments.

1 Comment

I think, that is the most used way, but I'm exited, if there are different options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.