React.JS — Component Data Transfer – codeburst

  • If you are passing data from somewhere in a component, to somewhere else inside the same component, this can be done through state.So what is state?The heart of every React component is its “state”, an object that determines how that component renders behaves.
  • That might look something like this:class component_A extends Component { constructor() { super(); this.state = { data: [], };}In this case, we are defining the state of data.
  • Passing data from parent to child components is only slightly trickier, in that, we can’t pass data in an unbroken chain to other components.
  • [callback] in the child, and pass in the data as an argument.From our above example, our code might look something like this:class component_A extends Component { constructor() { super(); this.state = { listDataFromComponent_C: “ “, };}myCallback = (dataFromComponent_C) = {this.setState({ dataFromComponent_C: dataFromComponent_C});Now from within the child component (component_C) we can pass something to props are static, while state can be changed, once you have passed data from a child to a parent, or from parent to a child, you may need to interact with it differently within that new component.
  • It might look like the following:class component_A extends Component {constructor = {dataFromComponent_C: “ “};},myCallback = (dataFromComponent_C) = {this.setState({ dataFromComponent_C: dataFromComponentC });This is just a brief explanation of how to change data within a component, and transfer data to other child and parent components.

In React JS, there’s often a need to pass data from one component to another. If you are passing data from somewhere in a component, to somewhere else inside the same component, this can be done…
Continue reading “React.JS — Component Data Transfer – codeburst”

Inline Form in HTML Table with React – Hajime Terasawa – Medium

  • Base Formimport React, { Component } from ‘react’;import PropTypes from ‘prop-types’;export default class BaseForm extends Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } // this.props.model.attrs を 初期state として持つ componentWillMount(){ const model = this.props.model; Object.keys(model).
  • map((attr) = { let initState = {}; initState[attr] = model[attr]; this.setState(initState); }); } // handleChange(name, e) { let newState = {}; newState[name] = e.target.value; this.setState(newState); } handleSubmit(e) { e.preventDefault(); } render() { const newChildren = React.Children.map( this.props.children, (child) = { switch (typeof child) { // case ‘string’: return child; // React要素だった場合は 初期値とcb を渡す case ‘object’: const newProps = { onChange: this.handleChange, value: this.state ?
  • this.state[child.props.name] || : }; return ( div / {React.cloneElement(child, newProps)} /div ); default: return null; } }); return ( form onSubmit={this.handleSubmit} { newChildren } button type=”submit” className=”btn btn-primary”Submit/button /form ); }}BaseForm.propTypes = { model: PropTypes.object, onSubmit: PropTypes.func}Table Inline Formimport React, { Component } from ‘react’;import PropTypes from ‘prop-types’;export default class TableInlineForm extends Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } // this.props.model.attrs を 初期state として持つ componentWillMount(){ const model = this.props.model; Object.keys(model).
  • map((attr) = { let initState = {}; initState[attr] = model[attr]; this.setState(initState); }); } // handleChange(name, e) { let newState = {}; newState[name] = e.target.value; this.setState(newState); } handleSubmit(e) { e.preventDefault(); } render() { const newChildren = React.Children.map( this.props.children, (child) = { switch (typeof child) { // case ‘string’: return child; // React要素だった場合は 初期値とcb を渡す case ‘object’: const newProps = { form: `form${this.props.formId}`, onChange: this.handleChange, value: this.state ?
  • this.state[child.props.name] || : }; return ( td {React.cloneElement(child, newProps)} /td ); default: return null; } }); return ( tr tdform onSubmit={this.handleSubmit} {this.props.model.id}/form/td { newChildren } tdbutton type=’submit’ className=’btn btn-primary’Submit/button/td /tr ); }}TableInlineForm.propTypes = { formId: PropTypes.string, model: PropTypes.object, onSubmit: PropTypes.func}変更があったのは render() メソッドのみ。本来 table 下に form を置くことは出来ないが、HTML5 の form attribute を props として input に付与することで実現できた。BaseForm 自体の実装はこれを参考にしている。React を書いていると生の HTML(実際には JSX ) を書く機会が増えるので、なんというか Web ページを作っている感があって楽しい。なにより component

現在 react の勉強がてら、昔作った rails アプリのSPR化を行っている。. “Inline Form in HTML Table with React” is published by Hajime Terasawa
Continue reading “Inline Form in HTML Table with React – Hajime Terasawa – Medium”

C’est la “Vue” – eMAG TechLabs – Medium

Neat article comparing the journey going from #reactjs to #vuejs

  • As you will see, it’s more about knowing what you want and not the number of articles that endorse a framework, the community or even the company behind it.HX TeamHX (Team) stands for Human Experience and was our team name of choice as it suggests the vision that we believe in: “Making intuitive and easy to use applications for all eMAG’s employees.”
  • The framework should have been used for internal applications in eMAG that adopts this architectural design style.Making the choice was not easy, so we’ve started with the following needs and expectations:Large community of developersFast DOM ChangesGreat architectureEasy debuggingTherefore we’ve chose React over Angular 2 (it was in Beta back then).
  • React was created to make DOM changes fast, really fast, so you will have to use React functions to make use of this, some of which you will not be familiar with (because React has a different architectural style)React plugins were not so much customizable as changing some of them required making a forkDon’t get me wrong, React is great, but only if you want to develop a simple application where the UI should not be consistent across different technologies or where DOM changes should be made really, really fast.Vue JSFinding meaning againAs we were put into the position of acknowledging that React doesn’t fit eMAG’s internal needs, we’ve come to discover Vue.js.Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces.
  • Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable.Vue was not only great, it was perfect for what we’ve wanted to do:It had an amazing boilerplate with dev and prod tasksIt had linters, libraries for unit and functional tests, all out of the boxIt could be used with jQuery (by making wrappers for plugins)It’s smallIt accepts FLUX architecture if you need itIt has an amazing template engineThe development is easyIt separates the template engine from components javascriptBy making the decision of using Vue we’ve managed to reduce the roadmap time by half (even starting from zero) compared to React.So after a month of hard work, we’ve made wrappers for our JQuery components from eMAG Apps UI Kit, created examples for them, simple unit tests, services all by having a clean code and RESTful APIs to test our frontend.React JS componentexport class Autocomplete extends React.Component {constructor(props) { super(props); this.state = { value: this.props.value || ”, } }componentWillMount() { this.options = this.
  • find(‘#date_time_’ + } catch (ex) {} } }/scriptConclusionNow we can say that when making a choice we have different criteria that we are looking for:Easy to useFamiliarCommunity (not so much plugins, but responses for issues)Reuse of our code

As technology is evolving at a fast pace and microservices are a thing now, the number of frontend libraries/frameworks that endorse this architectural design style has gone up to the roof. Making a…
Continue reading “C’est la “Vue” – eMAG TechLabs – Medium”

TDD is evil. Snapshot testing is the future. – Łukasz Sentkiewicz – Medium

TDD is evil. Snapshot testing is the future.  #javascript #tdd #testing #jest #react #reactjs

  • Simply add some tests, after you create the code.TDD in practiceLet’s take a look at an example article how to do TDD in React.Getting Started with TDD in React by @Dave CeddiaYou can find the final source in the GitHub repo.The task is to create a simple app with the following features:Allow to add new items (one string value).
  • When you have tests for the simple components that render a user’s name and email address (for example), you can later split that component up into pieces and be confident that it still works correctly.There are many uses cases where refactoring without changing functionality from the user perspective can break the tests.The original InputArea:export class InputArea extends Component { constructor(props) { super(props); this.state = { text: ” }; this.setText = this.setText.bind(this); this.handleClick = this.handleClick.bind(this); }setText(event) { this.setState({text: event.target.value}); }handleClick() { }render() { return ( div input value={this.state.text} onChange={this.setText}/ button /div ); }}Can be refactored and simplified to:export class InputArea extends Component { render() { const {onSubmit} = this.props; return ( div input ref={(input} = (this.input = input)} / button onClick={() = /div ); }}The functionality won’t change, but it will break some tests.Another TDD tutorial TDD and React Components by Will VaughnThe task is to create another simple app with the following features:display list of radio inputsget onSelection callback if the input is selectedThe created component is not well designed, and it shows that using TDD doesn’t make your design perfect.There are following problems.Using a component factory (React) = (props) = {…} .
  • Tests test something, but they won’t give you 100% guarantees that the implementation is correct.Few example:It’s not verified if the input have an attribute type=”radio” .
  • jsimport * as types from function addTodo(text) { return { type: types.ADD_TODO, text }}Testing usually looks like thisimport * as actions from * as types from () = { it(‘should create an action to add a todo’, () = { const text = ‘Finish docs’ const expectedAction = { type: types.ADD_TODO, text } })})The fastest way to produce such unit tests it’s just copying code between the test file and the target source file.
  • My TDD doesn’t work in “Red”, “Greed” way, but rather in “Red”, “Red”, “Red”, “Green” way.If you just do unit testing without TDD, it’s sometimes easier to get the output from console.log(result) and then put it to to TDDI started using Facebook Jest and I test everything with snapshots.My development process looks similar to TDD, but I am able to iterate much faster.Development cycleCreate a test case with an empty snapshot.describe(‘actions’, () = { it(‘addTodo’, () = { expect(”).

I’ve been participating in Topcoder for 4 years, and during this time I completed over 250 contests. We tried to use unit tests many times, and multiple members including copilots (Project Managers…
Continue reading “TDD is evil. Snapshot testing is the future. – Łukasz Sentkiewicz – Medium”

How to Build a ToDo App Using React, Redux, and Webpack

Build a to-do app using #ReactJS, #Redux, and #Webpack:

  • Let’s get started.TL;DRDownload the GitHub repo.Check out the demo.Getting Started:First, let’s make a new directory to build our project in and lets also make a package.json file.mkdir touch package.jsonNow, in your package.json, copy and paste the code below and then run npm install or yarn (if you’re a super cool yarn “name”: “cosmicToDo”, “version”: “1.0.0”, “description”: “A simple todo app thet uses the Cosmic JS API”, “main”: “index.js”, “scripts”: { “start”: “nodemon server/index.
  • js”, “build”: “webpack -w”, “test”: “echo \”Error: no test specified\” exit 1″ }, “author”: “”, “license”: “ISC”, “dependencies”: { “axios”: “^0.16.1”, “react”: “^15.5.4”, “react-dom”: “^15.5.4”, “react-redux”: “^5.0.4”, “redux”: “^3.6.0”, “redux-logger”: “^3.0.1”, “redux-thunk”: “^2.2.0”, “css-loader”: “^0.28.0” }, “devDependencies”: { “babel”: “^6.5.2”, “babel-core”: “^6.18.0”, “babel-loader”: “^6.2.7”, “babel-preset-es2015”: “^6.18.0”, “babel-preset-react”: “^6.16.0”, “cross-env”: “^3.1.4”, “nodemon”: “^1.11.0”, “volleyball”: “^1.4.1”, “webpack”: “^2.2.1”, “webpack-livereload-plugin”: “^0.10.0”, “sass-loader”: “^6.0.3”, “style-loader”: “^0.16.1” }}What we’re installing and why:We’re going to use the axios library to handle our requests to our Cosmic JS bucket.We’re installing react and react-dom to build our react components.We are going to use redux, react-redux, redux-logger, and redux-thunk to help us implement what is called the Flux architecture.The only thing worth mentioning in the dev dependencies is webpack and volleyball.
  • /reducer’;import thunkMiddleware from ‘redux-thunk’;import {createLogger} from ‘redux-logger’;const store = createStore( reducer, applyMiddleware( createLogger(), thunkMiddleware ));export default store;What’s going on here:We are setting up our redux “store” so that we can pass data down through “props” into whatever components we want (I am going to assume you have some working knowledge of how the flux architecture functions, if you do not understand this it is OK, just check the flux architecture link above).
  • /components/Home’;import {Provider} from ‘react-redux’;import store from Provider store={store} Home / /Provider, going on here:We are telling ReactDOM to target our “root” div from our index.html file and pop in our Home/ react component (which we will build out in our next step).
  • /Task’;class Home extends Component { constructor(props){ super(props); } componentDidMount(){ getAllTasks(); } render() { return ( div div className=”container” div className=”row” div className=”col-xs-12″ h1Cosmic To-Do App!!

In this tutorial I’m going to show you how to create a simple “ToDo” app using React, Redux, a little bit of Node, and Cosmic JS. For the sake of understanding how to consume Restful API’s, this…
Continue reading “How to Build a ToDo App Using React, Redux, and Webpack”

Understanding State and Props in React – Hacker Noon

Understanding State and Props in React @RuairidhWM  #JavaScript #Reactjs #WebDev

  • Understanding State and Props in ReactI’ve been playing around with React and Redux recently and thought I would start writing articles on concepts which I’ve had to wrap my head around.So unless you’ve been living in a cave for the past few years, you’ll know that React is an awesome front-end library developed by the good folks at Facebook to make life easier for developers.It’s different to Angular or other frameworks as it is purely front-end (though see the comments below for a great clarification on this).
  • With that said, it’s extremely powerful.One of the concepts I struggled to understand during my learning more about React was the interaction between State and Props.
  • If you’re at all familiar with React then you should know that props flow downwards from the parent component.There is also the case that you can have default props so that props are set even if a parent component doesn’t pass props down.This is why people refer to React as having uni-directional data flow.
  • What happens when a component receives data from someone other than the parent?
  • This is super cool because that means React takes care of the hard work and is blazingly fast.As a little example of state, here is a snippet from a search bar (worth checking out this course if you want to learn more about React)Class SearchBar extends Component { constructor(props) { super(props);this.state = { term: ” }; }render() { return ( div className=”search-bar” input value={this.state.term} onChange={event = / /div ); }onInputChange(term) { this.setState({term}); }}SUMMARYProps and State do similar things but are used in different ways.

I’ve been playing around with React and Redux recently and thought I would start writing articles on concepts which I’ve had to wrap my head around. So unless you’ve been living in a cave for the…
Continue reading “Understanding State and Props in React – Hacker Noon”

Understanding State and Props in React – Ruairidh Wynne-McHardy – Medium

Understanding State and Props in React  #javascript #development #react #es6 #reactjs

  • Understanding State and Props in ReactI’ve been playing around with React and Redux recently and thought I would start writing articles on concepts which I’ve had to wrap my head around.So unless you’ve been living in a cave for the past few years, you’ll know that React is an awesome front-end library developed by the good folks at Facebook to make life easier for developers.It’s different to Angular or other frameworks as it is purely front-end.
  • With that said, it’s extremely powerful.One of the concepts I struggled to understand during my learning more about React was the interaction between State and Props.
  • If you’re at all familiar with React then you should know that props flow downwards from the parent component.There is also the case that you can have default props so that props are set even if a parent component doesn’t pass props down.This is why people refer to React as having uni-directional data flow.
  • What happens when a component receives data from someone other than the parent?
  • This is super cool because that means React takes care of the hard work and is blazingly fast.As a little example of state, here is a snippet from a search bar (worth checking out this course if you want to learn more about React)Class SearchBar extends Component { constructor(props) { super(props);this.state = { term: ” }; }render() { return ( div className=”search-bar” input value={this.state.term} onChange={event = / /div ); }onInputChange(term) { this.setState({term}); }}SUMMARYProps and State do similar things but are used in different ways.

I’ve been playing around with React and Redux recently and thought I would start writing articles on concepts which I’ve had to wrap my head around. So unless you’ve been living in a cave for the…
Continue reading “Understanding State and Props in React – Ruairidh Wynne-McHardy – Medium”