call to ReactJS component in Laravel blade templates - laravel

I use Laravel 5.4 and React 15.5.4, code is writing in ES6.
I'd like replace Vue and use React and I did it. But I often will use small components for example 2 in different places of blade template. I don't want use one app component.
I'd like use something like:
<span class="react">
<TestComponent property={true} />
</span>
I can't do it automatically. Now I use
<span data-component="TestComponent" data-props="{property:true}" />
and in app.js
_.each(document.querySelectorAll('[data-react]'), element => {
let props ={};
Array.prototype.slice.call(element.attributes)
.forEach(item => {
props[item.name] = item.value;
if(item.name !== 'data-react'){
element.removeAttribute(item.name);
}
});
ReactDOM.render(React.createElement(reactComponents[element.getAttribute('data-react')],props),element);
});
It works but I need to use add all properties to one react component property and then use for example this.props.out.propery
I also would like set normal component tag in my blade component
I've try to use in app.js
_.each(document.querySelectorAll('.react'), item => {
ReactDOM.render(item.children,item);
});
Someone have any idea to solve this problem?
EDIT
I changed my solution to:
<span data-react="LoginForm" input="{{json(request()->old())}}" error="{{session('error')}}" errors="{{json($errors->getMessages())}}" />
or
<LoginForm data-react="LoginForm" input="{{json(request()->old())}}" error="{{session('error')}}" errors="{{json($errors->getMessages())}}" />
in blade and in resources/assets/js/app.js
var reactComponents = {
LoginForm: require('./components/login').default,
};
_.each(document.querySelectorAll('[data-react]'), element => {
let props ={};
Array.prototype.slice.call(element.attributes)
.forEach(item => {
props[item.name] = item.value;
});
ReactDOM.render(React.createElement(reactComponents[element.getAttribute('data-react')],props),element);
});
It works fine. This is not super clear solution but I have impression that the reasonable.
I can set components name in html code and add props almost same like in JSX.

As far as I know, you can not mix JSX components directly with Blade templates. The only server side rendering available today for React is NodeJS.
What you could do to improve your architecture is add specific HTML tags with certain ids and render the react components in them. So inside Blade you could do something like:
<div id="componentA"></div>
This will act as a place holder in your Blade template for that react component. Then you render your componentA from your app.js like this:
React.render(<ComponentA prop1='valueX'/>, document.getElementById("componentA"))
Remember that in this case the world of react and world of Blade run at different times.

You could use document.getElementsByTagName('LoginForm') getting all the instances and later iterate its attributes. It's clear code but not generic, because it will work just for LoginForm components.
If you want to render any tag name, then maybe it's better to use some attribute as you used with data-react.
getElementsByTagName isn't super supported by old browsers so maybe could a good idea to use jQuery as fallback $('LoginForm')

Related

How can I pass a variable from slot to its layout in Laravel?

I am using Laravel 8 and I can't find a way to solve this problem.
I have a app-layout like this:
<!-- ./app-layout.blade.php -->
<html>
<head>...</head>
<body>
<livewire:create-suggestion />
{{ $slot }}
</body>
</html>
And this view uses the app-layout:
<!-- ./index.blade.php -->
<x-app-layout>
...
</x-app-layout>
In controller, I pass a variable to index view:
public function index() {
return view('index', ['variable', '$variable']);
}
How can I pass this variable to the app-layout? Because I also want to
use this in the create-suggestion livewire component.
Try this. edit your index.blade.php
#extends('app-layout', ['variable' => $variable])
...
You can pass any variable attribute to the layout like so:
<x-layout :myvariable=$myvariable>
or static attribute values like so
<x-layout myvariable="This is a string">
and retrieve it in the layout.blade.php like so:
{{ $attributes['myvariable'] }}
First off I beleive the App Layout will have access to whatever is passed by the view function. But if I am wrong or you wish to pass any custom variable whatsoever using the Layout syntaxt as opposed to template inheritance the way would be: (I came cross your question having a problem passing a static string for my HTML page title and no solution worked until I found this)
<x-app-layout>
<x-slot:variable>{{$variable}}</x-slot>
</x-app-layout>
However your issue is you are using Livewire and livewire is not simply just a view! Laravel Intentionally makes Livewire independent from the rest of the page. You would have to either pass it in PHP as param during mount which will only be accessible if set during the mount function() in \App\HTTP\LiveWire\createSuggestion.php
#livewire("create-suggestion",[ $variable])
Or ideally you have your javascript use the $emit feature to pass the element to the livewire listener all handled via Livewire. It seems to me you are using Livewire for something that you should simply only use Blade/Views:
#include("create-suggestion");

Vue2 + laravel6 - Component implementation

I just started using Vue2 with Laravel6 and got stuck when trying to understand how to use component method.
As I am totally new for Vue, I am using the official tutorial of Vue as a reference. What I learned from here(https://v2.vuejs.org/v2/guide/components.html) about Vue component instantiation is we give options to a component.(e.g. we give 'template:' options for HTML part.)
When I look at laravel6 codes of resouces/js/app.js, it looks something like this:
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
I looked at js/components/ExampleComponent.vue expecting to see some options declared there. However, there's no option in the ExampleComponent.vue file. Instead, I see <template></template> tag. Apparently, the <template></template> tag seems to work as 'template:' option.
I have two questions regarding above:
Does <template></template> tag have the same meaning as 'template:' option?
If question 1 is yes, are other options also replacable with corresponding tags? (e.g. Can I use <props></props> tag for 'props:' option? or <data></data> tag for 'data:' option?
Thanks in advance!
In Vue world, there are two popular types of defining a component
First Type
in this type, you add all of your HTML inside the template property
and the props add as attribute inside the component object to
Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
Second Type
in this type you add your component logic in a separate file ends with .vue
for example in laravel there is an ExampleComponent.vue file you will find on
it just template tag just as a wrapper for your component content and your logic you can write it as it mentions below.
<template>
// some content here
</template>
<script>
export default {
props: [],
methods: {
},
data(){
return {
}
}
}
</script>
Finally
there is no tag called props or data
for more info read this article

how to pass laravel trans strings to vue component

In the event that you are developing your software using the Laravel framework and need to use the Vue library, you will face some obstacles, including how to access the files translation system provided by Laravel .
like how to access trans('home.var')
Add Language file like this
<messagings v-bind:language="{{ json_encode(trans('messages')) }}"></messagings>
then in vue component print like this
<h4>{{ this.language.messaging }}</h4>
1: pass trans as prop in blade normally just you need to encoding with json used json_encode() method :
<component :trans="{{json_encode(trans('home'))}}"></component>
2: in vue component page you need to decode json data first and set the translation data in some var :
export default {
props:['trans'],
data () {
return {
translation:[],
};
},
created(){
this.setTranslation()
},
methods:{
setTranslation(){
let decoded_trans = JSON.parse(this.trans);
this.transaction = decoded_trans;
}
}
3: Now you can access laravel trans normaly just be careful because vue will not detect if you call last node or first.
<template>
<div>
<h2>{{translation.header.login}}</h2> // this line in laravel mean : trans('home.header.login')
</div>
<template>
Finally I recently started learning vue , so this method may have some flaws, but We all strive to benefit :)

Best practice to pass data from Laravel to Vue component

This is my blade code
<div id="app">
<Testcomponent bam-wam="ham" />
</div>
This is my VueJS Component code
<script>
export default {
name: "ExampleComponent",
props: [
'bamWam'
],
data () {
return {
};
},
created() {
console.log(this.bamWam);
}
}
</script>
Question is
This code runs good but I am asking what is better using Axios and Vuex to fetch data from my Laravel app or simply Pass data throw props like I did in this code?
Pass data through props is the best way.
<my-component my-data="yourData"></my-component>
If you want to use laravel variable for data from blade then,
<my-component my-data="'{{ $data->id }}'"></my-component>
<my-component :my-data="'{!! json_encode($data) !!}'"></my-component>
Avoid api call as much as possible. It will reduce the total number of request to server and expose fewer number of api endpoint.
If the data is available to the view where the component is added. Then the best way to pass php arrays from laravel to a vue component is to utilize json encoding like so:
<my-component :needed-data='#json($laravelCollection)'></my-component>
This will make you will be easily to perform actions to the php array in the Vue controller as if it was a JS object. Keep in mind that you have to use single quotes for #json.
For simple strings you can just directly pass it as props without the encoding.
This approach is better than creating a new API specifically for this component.
This was the only way that works for me:
<my-component :data="{{ $collection }}"></my-component>
JSON parsed solutions prints data in HTML.

Binding Vue.js to all instances of an element, without(?) using Components

Today I'm learning Vue.js, and I have a few ideas of where it might be really useful in a new project that's an off-shoot of an existing, live project.
I like the idea of trying to replace some of my existing functionality with Vue, and I see that Components may be quite handy as quite a lot of functionality is re-used (e.g. Postcode lookups).
Once of the pieces of functionality I've used for an age is for invalid form elements - currently in jQuery when a form input or textarea is blurred I add a class of form__blurred, and that is coupled with some Sass such as:
.form__blurred {
&:not(:focus):invalid {
border-color:$danger;
}
}
This is to avoid styling all required inputs as errors immediately on page load.
I'm totally fine with doing this in jQuery, but I figured maybe it could be done in Vue.
I have an idea of how I might do it with components thanks to the laracasts series, but my form inputs are all rendered by Blade based on data received from Laravel and it doesn't seem like a neat solution to have some of the inputs rendered in Javascript, for a number of reasons (no JS, confusion about where to find input templates, etc).
I figured something like the following simplified example would be handy
<input type="text" class="form__text" v-on:blur="blurred" v-bind:class="{ form__blurred : isBlurred }" />
<script>
var form = new Vue({
el : '.form__input',
data : {
isBlurred : false
},
methods : {
blurred : function() {
this.isBlurred = true;
}
}
});
</script>
That actually works great but, as expected, it seems like using a class selector only selects the first instance, and even if it didn't, I'm guessing changing the properties would apply to all elements, not each one individually.
So the question is - is this possible with pre-rendered HTML, in a way that's smarter than just looping through a selector?
If it is, is there a way to create the Vue on a .form element and apply this function to both .form__input and .form__textarea?
Or, as is probably the case, is this just not a good use-case for Vue (since this is actually a lot more code than the jQuery solution).
Sounds like a great use case for a Custom Directive.
Vue allows you to register your own custom directives. Note that in Vue 2.0, the primary form of code reuse and abstraction is components - however there may be cases where you just need some low-level DOM access on plain elements, and this is where custom directives would still be useful.
<div id="app">
<input type="text" name="myforminput" v-my-directive>
</div>
<script>
Vue.directive('my-directive', {
bind: function (el) {
el.onblur = function () {
el.classList.add('form__blurred');
}
}
});
var app = new Vue({
el: '#app'
});
</script>
You can also add the directive locally to a parent component, if it makes sense for your application.

Resources