Search code snippets, questions, articles... Chrome Extension

reactjs code snippets

Loop n times in React
Array.apply(null, { length: 20 }).map((e, i) => (
  <span className="busterCards" key={i}>
    {e}
  </span>
));
Interview Question 1
/* Can you explain the differences between Component 1 and Component 2
 * Can you explain the differences between Component 2 and Component 3
 */

//Component 1
class Component1 extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.input = React.createRef();
  }

  handleSubmit(event) {
    alert("A name was submitted: " + this.input.current.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={this.input} defaultValue={"Bob"} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

//Component 2
//Here I am maintaining value in the state
class Component2 extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.updateValue = this.updateValue(this);
    this.state = { value: "Bob" }; //Different from Componenet1
    this.input = React.createRef();
  }

  handleSubmit(event) {
    alert("A name was submitted: " + this.state.value);
    event.preventDefault();
  }

  //Different from Componenet1
  updateValue(e) {
    const value = e.target.value;
    this.setState({ value }); //Change value in state
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input
            type="text"
            ref={this.input}
            value={this.state.value} //Different from Componenet1
            onChange={this.updateValue} //Different from Componenet1
          />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

//Component 3
class Component3 extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.updateValue = this.updateValue(this);
    this.state = { value: "Bob" };
    this.input = React.createRef();
  }

  handleSubmit(event) {
    alert("A name was submitted: " + this.state.value);
    event.preventDefault();
  }

  //Different from above component
  updateValue(e) {
    const value = e.target.value;
    this.state.value = value; //Change value in the state
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input
            type="text"
            ref={this.input}
            value={this.state.value}
            onChange={this.updateValue}
          />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
[React]Add or push values to array defined in state
var newArr = this.state.arr.concat('new value');
this.setState({ myArray: newArr });

//USING es6 IT CAN BE DONE PRETTY EASILY

//PUSH ITEM TO THE END OF AN ARRAY
this.setState({
    arr: [...this.state.arr, "new value"]
});

//ADD NEW ARRAY AS A LAST ELEMENT
this.setState({
    arr: [...this.state.arr, ["a", "b", "c"]]
});

//PUSH OBJECT OR ITEM TO THE START OF ARRAY
this.setState({
    arr: [{"name": "value"}, ...this.state.arr]
});
Bind form or input elements with state in React
class CName extends Component {
    constructor() {
        this.state = {
            firstname: ''
        }
    }

    handleInputChange = (e) => {
        this.setState({
            firstname: e.target.value
        });
    }

    render() {
        return (
            <div>
                <input type="text" value={this.state.firstname} onChange={this.handleInputChange} />
            </div>
        );
    }
}
Create new react app commands
npx create-react-app app_name
cd app_name
npm start
Add CSS class dynamically in React
class Hello extends React.Component {
    render() {
        return (
            <div>
                <div className={"first_class " + (this.state.val ? "true_class" : "false_class") + " another_class" }>First Method</div>
                <div className={`container box ${this.state.something}`}>Second Method</div>
                <div className={'container box ' + this.state.something}>Third Method</div>
            </div>
        );
    }
}
Render components after asynchronous call in React
class CardComponent extends Component {
    componentDidMount() {
        const self = this;
        api.getData(data => self.setState({ articleData: data }));
    }

    render() {
        return (
            <div>
                <h1>{'This will always render'}</h1>
                { this.state && this.state.articleData &&
                    <div>{'This will render after the return of the async call'}</div>
                }
            </div>
        )
    }
}
Map State to Props using React + Redux
import React from "react";
import { connect } from "react-redux";

const mapStateToProps = state => {
    return { articles: state.articles };
}

const ConnectedList = ({ articles }) => (
    <ul>
        { articles.map(article => (
            <li className="item" key={article.id}>{ article.title }</li>
        )) }
    </ul>
);

const List = connect(mapStateToProps)(ConnectedList);


class FirstComponent extends React.Component {
    render() {
        return (
            <div>
                <div className="Hello">Hello ankit this i</div>
                <List></List>
            </div>
        );
    }
}

export default FirstComponent;
Create new component in React
// CREATE CLASS NAMED AS COMPOENT NAME
class ComponentName extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            prop_name: 'value',
            prop_name2: `Hello ${this.props.name}, `
        }

        this.onChange = this.onChange.bind(this); //IF YOU WANT TO USE 'this' KEYWORD
    }
    
    onChange(e) {
        this.setState({
            prop_name: e.target.value
        })
    }

    render() {
        return (
            <div>
                <p className="sample_class">{ this.state.prop_name }</p>
                <input className="input_ctrl" name="name" placeholder="Enter text" onChange={this.onChange} />
            </div>
        )
    }
}

ReactDOM.render(<ComponentName name="Your name" />, document.getElementById('app'));