Search code snippets, questions, articles...

reactjs code snippets

Loop through an object using map in React
const subject = {
    name: 'Math',
    score: 98,
    sub_code: 'M01',
    teacher_name: 'Ramanujam',
};

return (
    <div>
        {Object.keys(subject).map(key => (
            <div key={key}>
                {key}: {subject[key]}
            </div>
        ))}
    </div>
);
Custom hook to check window is visible
import { useEffect, useState } from 'react'

const VISIBILITY_STATE_SUPPORTED = 'visibilityState' in document

function isWindowVisible() {
  if (!VISIBILITY_STATE_SUPPORTED) {
    return true
  }

  return document.visibilityState === 'visible'
}

/**
 * Returns whether the window is currently visible to the user.
 */
export default function useIsWindowVisible() {
  const [isVisible, setIsVisible] = useState(isWindowVisible())

  useEffect(() => {
    if (!VISIBILITY_STATE_SUPPORTED) return undefined

    const handleVisibilityChange = () => {
      setIsVisible(isWindowVisible())
    }

    document.addEventListener('visibilitychange', handleVisibilityChange)
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange)
    }
  }, [setIsVisible])

  return isVisible
}
dsada
// Calling a server-side action
({
    callServerSideAction : function(cmp) {
        // 1. Retrieve an action object by specifying the
        //    Apex method that will be called
        let action = cmp.get("c.myApexEndpoint");

        // 2. Optionally set some action parameters
        action.setParams({ firstName : cmp.get("v.firstName") });

        // 3. Configure a callback function that will be
        //    executed to handle the server response
        action.setCallback(this, function(response) {
            // Some response processing code
        });

        // 4. Optionally set some action configuration flags

        // 5. Enqueue the action so that the framework processes it
        $A.enqueueAction(action);
    }
})
Nullish coalescing operator (??)
const nullValue = null
const valA = nullValue ?? "default for A"
How to use loop in React JSX
//USING FOR LOOP
<tbody>
    for (var i=0; i < items.length; i++) {
        <TableRow obj={items[i]} key={i}>
    }
</tbody>

//USING map function
<tbody>
    {items.map(function(item, index) {
        return <TableRow obj={item} key={index} />;
    })}
</tbody>

//ES6 SYNTAX
<tbody>
    {items.map((item, index) => <TableRow obj={item} key={index} />)}
</tbody>
Deploy React application from subdirectory
// OPEN  package.json FILE AND ADD "homepage": "/folder-name/"
{
    "name": "app name",
    "version": "0.1.0",
    ...
    "homepage": "/folder-name/" //ADD THIS AT THE BOTTOM
}

//OPEN ROUTING FILE AND ADD basename={'folder-name'}
<Router history={browserHistory} basename={'folder-name'}>
  <Route path="/" component={App} />
</Router>
Navigate or link to another page React
//INSTALLATTION - npm install react-router-dom
import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

export default function App() {
    return (
        <div>
            <ul>
                <li><Link to="/">Home</Link></li>
                <li><Link to="/about">About</Link></li>
                <li><Link to="/contact">Contact</Link></li>
            </ul>

            <Router>
                <Route exact path="/" component={Home} />
                <Route exact path="/about" component={About} />
                <Route exact path="/contact" component={Contact} />
            </Router>
        </div>
    );
}
Render item condition based React
function template() {
    const renderItem = true;

    return <div>
        {renderItem &&
            <div>This will render if renderItem is true</div>
        }
    </div>
}
Get index in map React
function items() {
    const nums = [1, 2, 3, 4];
    return <div>
        {nums.map( (num, index) => 
            <div key={index.toString()}>{num}</div>
        )}
    </div>;
}
List and map in React
function subjectList() {
    const subjects = [
        {"name": "Physics", "score": "9"},
        {"name": "Chemistry", "score": "7"},
        {"name": "Math", "score": "10"}
    ];
    const subjectItems = subjects.map( (subject, index) =>
        <div class="item" key={index.toString()}>
            Subject is {subject.name}
            Score is {subject.score}
        </div>
    );
    return <div class="items">{subjectItems}</div>
}
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'));