reactjs datagrid use html - datagrid

Im using the datagrid component here
I would like to use html in one of the fields and show a link or a picture etc.
I tried using the render function for the column as below
var columns = [
{ name = 'field' },
{ name = 'link',render : function(uri) { return 'link'} },
];
however it prints out the html as text

This is because by default React escapes HTML, in order to prevent XSS attacks. You can by pass this, by using the prop dangerouslySetInnerHTML, as described here.
However, as the name suggests, this leads to a vulnerability. I would suggest instead to use Mardown, especially the marked package.
You can write a general component like this one and then use it everywhere.
import React from 'react';
import marked from 'marked';
const Markdown = React.createClass({
render() {
const raw = marked(this.props.text, {sanitize: true});
return <span dangerouslySetInnerHTML={{__html: rawMarkup}} />;
}
});
In your case then
var columns = [
{ name = 'field' },
{ name = 'link', render : function(uri) { return <Markdown text={'[link](' + uri + ')'} />} },
];

First I created a class which will output a link
var Linkify = React.createClass({
render : function(){
return (
<a href={this.props.link}>{this.props.title}</a>
)
},
});
Then used this class in the render function
var columns = [
{ name : 'edit', render : function(id){
var editlink = "http://www.example.com/id="+id;
return ( <Linkify link={editlink} title="edit" />)
}
},
This way any html can be used in the datagrid column by simply using the react component.

Related

Wordpress Gutenberg Anchor Support for Dynamic Block

I want to have anchor support for my dynamic wordpress block. I did
//in registerBlockType
supports: {
anchor: true,
},
This adds the HTML Anchor control under the sidebar panel.
My block is a dynamic block that has
save: ( props ) => {
return <InnerBlocks.Content />;
}
I tried everything to get the anchor attribute to to frontend. According to this github issue I should add
anchor: {
type: 'string',
source: 'attribute',
attribute: 'id',
selector: '*',
},
to the blocks attributes. This will make the anchor available in the save function via props.anchor, however it never appears in my render_callback $attributes.
This is basically a port of the github issue to SO. Hope anyone can help here.
if anyone is still interested this worked for me:
so this is my custom block registering, this statement will enable standard wordpress HTML anchor field (with valuable validation for spaces etc.) under Advanced tab of selected gutenberg block:
supports: {
anchor: true
}
then in the same place we define:
attributes: {
anchor: {
type: 'string'
}
}
then in save function (I have it exactly for the same purpose of InnerBlocks):
save: function(props) {
const { anchor } = props.attributes;
return (
el( anchor, {}),
el( InnerBlocks.Content, {})
);
}
if you are using jsx, the save function could look like this:
save: function(props) {
const { anchor } = props.attributes;
return (
<div id={anchor}>
<InnerBlocks.Content />
</div>
);
}
then in your render callback function (in php) it's going to be available via first arg's (which is array) element
function your_callback( $block, $content ) {
// display your anchor value
echo $block['anchor'];
}
You could use this filter (targeting whatever blocks you want)
const withAnchor = props => {
if (props.attributes) { // Some blocks don't have attributes
props.attributes = {
...props.attributes,
anchor: {
type: 'string'
}
}
}
return props
}
wp.hooks.addFilter(
'blocks.registerBlockType',
'namespace/with-anchor',
withAnchor
)
And then you can access the 'anchor' attribute in the render callback
'render_callback' => function($attributes) {
echo $attributes['anchor'];
}
Have you tried manually adding a field that will take care of the ID attribute?
Something like this:
<InspectorControls>
<PanelBody title={ __( 'Element Settings' ) }>
<TextControl
label={ __( 'Element ID', 'fleximpleblocks' ) }
value={ elementID}
placeholder={ __( 'Type in the element ID…' ) }
onChange={ ( value ) => setAttributes( { elementID: value } ) }
/>
</PanelBody>
</InspectorControls>
And then:
save: ( props ) => {
return <InnerBlocks.Content id={ props.attributes.elementID } />;
}
I'm not sure if it'll work, I'm just taking a wild guess here. Let me know how it goes :)
Based on answers above.
You just need create an attribute which collects all other attributes/variables/whatever into string.
Step 1
Create an attribute with string type(in block.json)
"phpRender": {
"type": "string"
}
Step 2
In the "edit" function of the block, create a function to save whatever you need to the attribute above. Put this function in "useEffect" hook.
const saveAllToString = () => {
const blockProps = {
id: attributes.anchor,
}
setAttributes({phpRender: JSON.stringify(blockProps)});
}
useEffect(() => {
saveAllToString();
});
Step 3
Now you can decode this string and use variables easily.
$blockProps = !empty($attributes['phpRender']) ? json_decode($attributes['phpRender']) : false;
echo $blockProps->id;

alternative for jquery css in vuejs

I'm learning vuejs and trying to do all without jquery
I need to get a value of a css style line-height.
In jquery i would do:
let x = $(this).css("line-height");
How can I get this value using vuejs 2.5?
I was exploring this.$el in this structure, but can't find solution to get this value:
data: function () {
return {
lineHeight: null
}
},
mounted(){
this.lineHeight = ?
}
tl;dr
// with jQuery: $(this).css("line-height");
// with Vue:
mounted() {
this.lineHeight = window.getComputedStyle(this.$el).getPropertyValue('line-height');
}
If the component (this.$el) may be inside an iframe or popup, or if you want to be extra careful, read on.
JSFiddle demo here.
new Vue({
el: '#app',
data: {
lineHeightTLDR: '',
lineHeightFull: '',
},
mounted(){
this.lineHeightTLDR = window.getComputedStyle(this.$el).getPropertyValue('line-height');
this.lineHeightFull = this.css('line-height');
},
methods: {
css(propertyName) {
let view = this.$el.ownerDocument.defaultView;
if ( !view || !view.opener ) {
view = window;
}
let computed = view.getComputedStyle(this.$el);
return computed.getPropertyValue(propertyName) || computed[propertyName];
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<pre>lineHeight tl;dr..: {{ lineHeightTLDR }}</pre>
<pre>lineHeight full...: {{ lineHeightFull }}</pre>
</div>
Background
Simplest way to mimic jQuery is just to take a look at its source. The returned value from .css() is, roughly:
ret = computed.getPropertyValue( name ) || computed[ name ];
Which uses CSSStyleDeclaration.getPropertyValue on computed. And computed is:
return function( elem ) {
var view = elem.ownerDocument.defaultView;
if ( !view || !view.opener ) {
view = window;
}
return view.getComputedStyle( elem );
}
Which uses Window.getComputedStyle() As you can see, the returned value is something around:
ret = view.getComputedStyle(elem).getPropertyValue( name ) || view.getComputedStyle(elem)[name];
Where view is most probably window but could be something else (elem.ownerDocument.defaultView).
In the end of the day, if you want to be extra certain and do very close to jQuery.css(), use:
// with jQuery: $(this).css("line-height");
// with Vue:
mounted(){
this.lineHeight = this.css('line-height');
},
methods: {
css(propertyName) {
let view = elem.ownerDocument.defaultView;
if ( !view || !view.opener ) {
view = window;
}
let computed = view.getComputedStyle(this.$el);
ret = computed.getPropertyValue(propertyName) || computed[propertyName];
}
}
But if you know your usage does not rely on iframes or popups (as it is very unusual for a Vue instance JavaScript code to run at a window and have the $el it is attached to on another), go with the tl;dr version.

Selecting a Row in React Griddle, and changing tr background color

I'm just wondering if someone has already been able to change the color of a row, in React Griddle, by clicking on it (just once).
I'm experimenting things with JQuery, and even with Griddle Metadata, but it may be done in a cleaner way ?
Edit : I'm using React 15, Griddle inside MantraJS/Meteor, getting the data in my react Component using a Mantra container.
I can get the data by using onClick event, but not able to switch the background color in the onClick event, or playing with Metadatas.
Thanks !
EDIT : I use another view to display the content of the table, so for now I don't need to change the background of my tables cells, but if I found a solution I'll complete this post
You can use react-griddle props rowMetadata and onRowClick to do this:
class ComponentWithGriddle extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedRowId: 0,
};
}
onRowClick(row) {
this.setState({ selectedRowId: row.props.data.id });
}
render() {
const rowMetadata = {
bodyCssClassName: rowData => (rowData.id === this.state.selectedRowId ? 'selected' : ''),
};
return (
<Griddle
...
rowMetadata={rowMetadata}
onRowClick={this.onRowClick.bind(this)}
/>
);
}
}
Now this adds a selected class to the selected <tr> elements, so you can use custom styles to add colors or whatever styles you want to apply to the selected row.
Note that a more convenient API for selecting rows has been called for in the Griddle Github issues.
For whatever reason, I couldn't get Waiski's answer to work for me at all. I'm assuming that something must have changed in Griddle over the past two years. It looks like the current prevailing advice on the Web is to "implement row selection as a plugin", but I couldn't find any examples of that either. After a long hard look at the code for the Position plugin’s TableEnhancer on GitHub and a bunch of trial and error I eventually managed to cobble together the following row selection plugin for Griddle in TypeScript:
import * as React from "react";
import * as Redux from "redux";
import Griddle, { connect, GriddlePlugin, components } from "griddle-react";
export type RowId = string | number;
export type RowClickHandler = (event: React.MouseEvent<Element>, rowId: RowId) => void;
export type RowIdGetter<TData> = (rowData: TData) => RowId;
export interface IRowEnhancerProps {
rowClickHandler: RowClickHandler;
rowId: RowId;
isSelected: boolean;
}
export class RowSelector<TData> {
private _rowClickHandler: RowClickHandler = null;
private _rowIdGetter: RowIdGetter<TData>;
constructor(rowClickHandler: RowClickHandler, rowIdGetter: (rowData: TData) => RowId) {
this._rowClickHandler = rowClickHandler;
this._rowIdGetter = rowIdGetter;
}
public rowIdToSelect: RowId;
public plugin: GriddlePlugin = {
components: {
RowEnhancer: (OriginalComponent: React.ComponentClass<components.RowProps>) =>
this.rowSelectionEnhancer(OriginalComponent)
}
}
private rowSelectionEnhancer(
OriginalComponent: React.ComponentClass<components.RowProps>
): React.ComponentClass<components.RowProps> {
const rowDataSelector = (state, { griddleKey }) => {
return state
.get('data')
.find(rowMap => rowMap.get('griddleKey') === griddleKey)
.toJSON();
};
return Redux.compose(
connect((state, props) => {
const rowData: TData = rowDataSelector(state, props as { griddleKey });
const rowId: RowId = this._rowIdGetter(rowData);
return {
...props,
rowClickHandler: this._rowClickHandler,
rowId: rowId,
isSelected: rowId.toString() === this.rowIdToSelect.toString()
};
})
)(class extends React.Component<IRowEnhancerProps, any>{
public render() {
return (
<OriginalComponent
{...this.props}
onClick={(event) => this.props.rowClickHandler(event, this.props.rowId)}
className={this.props.isSelected ? "selected" : ""}
/>
);
}
});
}
}
Here's a rough outline of how it's used by a component. (Note that I had to selectively extract this example from a much larger and more complicated component, so there might be some errors/inconsistencies; sorry about that. It should still give a good overall idea of the approach.)
import * as React from "react";
import Griddle, { RowDefinition, plugins, GriddlePlugin} from "griddle-react";
import * as MyGriddlePlugins from "../GriddlePlugins";
export interface IPartInfo {
serialNumber: number,
name: string,
location: string
}
export interface IPartListProps{
parts: IPartInfo[],
selectedSerialNumber: number
}
export class PartList extends React.Component<IPartListProps, void > {
private rowSelector: MyGriddlePlugins.RowSelector<IPartInfo>;
private rowIdGetter: MyGriddlePlugins.RowIdGetter<IPartInfo>;
constructor(props?: IPartListProps, context?: any) {
super(props, context);
this._rowClickHandler = this._rowClickHandler.bind(this);
this.rowSelector = new MyGriddlePlugins.RowSelector(
this._rowClickHandler,
this._rowIdGetter);
}
private _rowClickHandler: MyGriddlePlugins.RowClickHandler =
(event: React.MouseEvent<Element>, selectedSerialNumber: MyGriddlePlugins.RowId) => {
if (selectedSerialNumber !== this.props.selectedSerialNumber) {
/*
Set state, dispatch an action, do whatever. The main point is that you
now have the actual event from the click on the row and the id value from
your data in a function on your component. If you can trigger another
render pass from here and set a fresh value for this.rowSelector.rowIdToSelect
then the "selected" CSS class will be applied to whatever row this click
event just came form so you can style it however you like.
*/
}
}
private _rowIdGetter: (rowData: IPartInfo) => MyGriddlePlugins.RowId =
(rowData: IPartInfo) => rowData.serialNumber;
public render(): JSX.Element {
this.rowSelector.rowIdToSelect = this.props.selectedSerialNumber;
return (
<div>
<Griddle
data={this.props.parts}
plugins={[plugins.LocalPlugin, this.rowSelector.plugin]}
>
<RowDefinition>
<ColumnDefinition id="name" title="Part Name" />
<ColumnDefinition id="location" title="Installed Location" />
<ColumnDefinition id="serailNumber" title="Serial Number" />
</RowDefinition>
</Griddle>
</div>
);
}
}
So, what's actually going on here? The component creates an instance of the plugin class at instantiation time, passing in an event handler to capture the click on the row and an accessor function to retrieve your ID value (not an inscrutable internal ID) from a row of your data. Just before the component returns its rendering, a value is set on the component's instance of the plugin, that way, when Griddle renders the plugin has the data to figure out when it's on a selected row and then adjust the CSS accordingly. The handler function from your component is then assigned to the row's onClick handler so your component can get the data from the click and do whatever it needs to do.
This passes the "It works for me" test (on React 15.6) which in my case is a straightforward master/detail view driven by a traditional table implemented through Griddle. I have no idea how well it would work with some of Griddle's more advanced features.

(Meteor + React) Cannot access props from within subcomponent

I am passing data from one component to another (MyApplicants) via my router (FlowRouter):
FlowRouter.route('/applicants', {
name: 'Applicants',
action: function () {
var currentUser = Meteor.user();
ReactLayout.render(App, {
content: <MyApplicants institutionID={Meteor.user().profile.institutionID} />,
nav: <Nav />,
header: <Header />
});
}
});
As you can see I'm passing institutionID to the new component via a prop in the router. I know that the institutionID is being passed because I can see it in the render of the MyApplicants component.
Here is the MyApplicants component:
MyApplicants = React.createClass({
mixins: [ReactMeteorData],
pagination: new Meteor.Pagination(Applicants, {
perPage: 25,
filters: {institution_id: this.props.institutionID },
sort: {institution_id: 1, "last_name":1, "first_name":1}
}),
getMeteorData() {
return {
currentUser: Meteor.user(),
applicants: this.pagination.getPage(),
ready: this.pagination.ready()
}
},
RenderApplicantRow(applicant, key) {
return (
<div key={key}>
<p>[{applicant.institution_id}] {applicant.last_name}, {applicant.first_name}</p>
</div>
)
},
render : function () {
return (
<div>
<section className="content">
{this.data.applicants.map(this.RenderApplicantRow)}
{console.log(this.data.applicants)}
<DefaultBootstrapPaginator
pagination={this.pagination}
limit={6}
containerClass="text-center"/>
</section>
</div>
)
}
});
(FYI, I'm using krounin:pagination.) The problem is that I cannot access this.props.institutionID inside of the pagination component. I know the value is getting passed (I can see it if I'm just testing output in the render) but can't figure out why it doesn't pass into the pagination call. And I know the pagination works because I do not get an error if I hard code in a value.
Thanks for the help.
This is a simple scope problem I think, you need to bind it to the right context
Try something like this:
pagination: function() {
var self= this;
new Meteor.Pagination(Applicants, {
perPage: 25,
filters: {institution_id: self.props.institutionID },
sort: {institution_id: 1, "last_name":1, "first_name":1}
})
}
,

How to implement Full Text Search in Meteor/Telescope

I have attempted implementing search in Telescope using pure javascript, since it looks like FTS is a while off for Meteor to implement and I couldn't get 2.4 playing nicely with Meteor yet.
I'm using the existing pagination model that is already implemented in Telescope to display the Top/New/Best posts, plus a Session variable for the search keyword that is set in the Router when you navigate to e.g. /search/foobar.
However, it doesn't quite seem to be working; when I have, say, 100 posts, the regular paginated subscription only comes back with 25 of these and my search results only show the posts in the first 25.
I've been banging my head against a wall for days trying to debug this one: sometimes it works, sometimes it doesn't!
Here's the code (I've included all additional search code for reference):
app.js:
var resultsPostsSubscription = function() {
var handle = paginatedSearchSubscription( 10, 'searchResults' );
handle.fetch = function() {
return limitDocuments( searchPosts( Session.get( 'keyword' ) ), handle.loaded() );
};
return handle;
};
var resultsPostsHandle = resultsPostsSubscription();
paginated_sub.js:
I duplicated the existing paginatedSubscription because I can't pass a Session var in as an arg; it needs to be dynamic. I'll probably refactor later.
paginatedSearchSubscription = function (perPage/*, name, arguments */) {
var handle = new PaginatedSubscriptionHandle(perPage);
var args = Array.prototype.slice.call(arguments, 1);
Meteor.autosubscribe(function() {
var subHandle = Meteor.subscribe.apply(this, args.concat([
Session.get( 'keyword' ), handle.limit(), function() { handle.done(); }
]));
handle.stop = subHandle.stop;
});
return handle;
}
search.js: (new file, in /common directory)
// get all posts where headline, categories, tags or body are LIKE %keyword%
searchPosts = function( keyword ) {
var query = new RegExp( keyword, 'i' );
var results = Posts.find( { $or: [ { 'headline': query }, { 'categories': query }, { 'tags': query }, { 'body': query } ] } );
return results;
};
publish.js:
Meteor.publish( 'searchResults', searchPosts );
posts_list.html:
<template name="posts_results">
{{> posts_list resultsPostsHandle}}
</template>
posts_list.js:
Template.posts_results.resultsPostsHandle = function() {
return resultsPostsHandle;
};
router.js:
there's a search bar in the nav that redirects to here
posts_results = function( keyword ) {
Session.set( 'keyword' , keyword );
return 'posts_results';
};
Meteor.Router.add({
...
'/search/:keyword':posts_results,
...
})
Any help would be greatly appreciated!
A little late but here is a full write up on how to implement full text search in meteor.
"The simplest way without editing any Meteor code is to use your own mongodb."

Resources