Key concept and Its necessities in React component – Shubham Akodiya – Medium

Key concept and Its necessities in React component  #es6 #react #reactjs

  • /ChildKey’;class ParentKey extends Component { constructor() { super(); this.state = {activeIndex: 0}; } updateIndex = () = { const {activeIndex} = this.state; this.setState({activeIndex: activeIndex + 1}) }getContent() { const {activeIndex} = this.state; let element; switch(activeIndex) { case 0: element = ChildKey name=’abc’ updateData={this.updateIndex} / break; case 1: element = ChildKey…
  • getContent() method returns the ChildKey component as per the activeIndex value.So Because the activeIndex default value initially set to 0, The initially getContent method returnselement = ChildKey name=’abc’ ChildKey component, we’ve initiallize the state i.e state = {childName: props.name} and when clicking on change parent component state link, then parent…
  • So name ‘bcd’ is printed and the element var becmes like below -element = ChildKey name=’bcd’ here we’re not using the key props, In ChildKey component.
  • Here react assuming both are same, So when constructor is call (constructor is called only one time in component life cycle), It initializes the state childName to ‘abc’ and In second time (when activeIndex changes to 1) constructor is not called, because react don’t know that It is separate component….
  • /ChildKey’;class ParentKey extends Component { constructor() { super(); this.state = {activeIndex: 0}; } updateIndex = () = { const {activeIndex} = this.state; this.setState({activeIndex: activeIndex + 1}) }getContent() { const {activeIndex} = this.state; let element; switch(activeIndex) { case 0: element = ChildKey name=’abc’ key=’23422%%%%’ updateData={this.updateIndex} / break; case 1: element =…

Most of the user had faced the problem of ‘key error’ i.e Warning: Each child in an array or iterator should have a unique “key” prop. Check the render method of xyz component, while using the custom…
Continue reading “Key concept and Its necessities in React component – Shubham Akodiya – Medium”

Controlled Forms in React – Byte-sized React – Medium

Controlled Forms in React  #tech #webdevelopment #programming #javascript #react #reactjs

  • Defining a form’s input value via state is considered a controlled component.For controlled inputs you will need a corresponding state and then a class method to update that state with changes.Let’s walk through a quick example with CodePen.
  • If you don’t know how to set up CodePen with React, you can check out this story.Let’s also add Boostrap 4 to our CodePen so our forms aren’t so plain.Add this to your JS file:class App extends React.Component { constructor(props) { super(props); } render() { return ( div className=”form-group container” labelControlled Form Input/label input type=”text” className=”form-control” aria-describedby=”emailHelp” placeholder=”Update input here” / large className=”form-text text-muted” Form Output /large /div ); }}ReactDOM.render( App /, your CodePen should look like this:Right now our form input is not controlled- meaning that the value of the form input is not determined by the state.
  • Let’s add a state value for the form making it a controlled form.Declare the state value in your constructor.constructor(props) { super(props); this.state({input: ”}); }Then let’s pass the state input value down to the value of the email form and as the value of our output text.input type=”text” className=”form-control” aria-describedby=”emailHelp” placeholder=”Update input here” value={this.state.input}/ large className=”form-text text-muted” {this.state.input} /largeNow notice how the value of the form reflects the state, but the form value doesn’t update.
  • Let’s add a method to update state, and pass it down using the onChange event handler.Add the method to your constructor.constructor(props) { super(props); this.state = ({input: ”}); this.formUpdate = define the formUpdate method.formUpdate(event) { this.setState({input: event.target.value});}The formUpdate function needs to be called whenever a change is made to the form input.
  • Use the onChange react event to trigger the formUpdate method.input type=”text” className=”form-control” aria-describedby=”emailHelp” placeholder=”Update input here” value={this.state.input} time a change happens to the form the formUpdate method will be called with the event object.

Form input values can be set to state values and then updated via React events. Defining a form’s input value via state is considered a controlled component. For controlled inputs you will need a…
Continue reading “Controlled Forms in React – Byte-sized React – Medium”

React Components Explained – Manoj Singh Negi – Medium

“React Components Explained” by @manojnegiwd  #reactjs #NodeJS #javascript #coding

  • Something like thisimport React from ‘react’;class MyComponent extends React.Component { render () { return div This is a component /div }}class MyOtherComponent extends React.Component { render () { return ( div MyComponent / /div ) }}This way you are able to compose more complex and useful user interface for your users.
  • Component’s render method return JSX which then use to create real HTML output which will be rendered in the browser.The interesting Thing about render method is that it runs every time when your component State or Props updates.
  • Let me show you a exampleimport React from ‘react’;class MyComponent extends React.Component { constructor(props) { super(props); this.state = { name: “Manoj” }; } render () { return div My name is {this.state.name} /div }}// if we render this component the output will beMy name is ManojIgnore the super(props) (out of the scope of this article) focus on this.state this is where our component state lives.
  • Let’s see an example.class MyComponent extends React.Component { constructor(props) { super(props); this.state = { name: “Manoj” }; this.changeName = this.changeName.bind(this); } changeName () { this.setState({ name: “Your Name” }); } render () { return div onClick={this.changeName} My name is {this.state.name} /div }}In the above code we are telling our React component to call this.changeName whenever user clicks on the div.
  • You can run this code on jsFiddle here.PropsVisualise props as options that can be passed to a component to customize its functionality.For example, I have a heading component which renders a heading with subtitle.class MyHeading extends React.Component { render () { return div h1This is a heading/h1 pSubtitle/p /div }}If I will use this component it will always render same HTML, someting like this.This is a headingsubtitleIf we use our component in this way it is not of much use right ?

The simplest library I ever used in my life is React. As you know React hit is based upon component design. Everything in React is a component which makes it easy to reuse components frequently. You…
Continue reading “React Components Explained – Manoj Singh Negi – Medium”

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”