reactjs code snippets

React Navbar
//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>
    );
}
Web Page with 3 cards Displaying images
import React from 'react';

const Card = (props) => {
  return (
    <div style={{ width: '30%', display: 'inline-block', margin: '16px' }}>
      <img src={props.image} style={{ width: '100%' }} />
      <div style={{ padding: '16px' }}>
        <h3>{props.title}</h3>
        <p>{props.text}</p>
      </div>
    </div>
  );
};

const App = () => {
  return (
    <div>
      <Card
        image="https://via.placeholder.com/300x200"
        title="Card 1"
        text="Lorem ipsum dolor sit amet, consectetur adipiscing elit."
      />
      <Card
        image="https://via.placeholder.com/300x200"
        title="Card 2"
        text="Lorem ipsum dolor sit amet, consectetur adipiscing elit."
      />
      <Card
        image="https://via.placeholder.com/300x200"
        title="Card 3"
        text="Lorem ipsum dolor sit amet, consectetur adipiscing elit."
      />
    </div>
  );
};

export default App;
Create a Modal Popup Component in React
import React, { useState } from 'react';
import './modal.css';

function ModalPopup({ children, title }) {
    const [isOpen, setIsOpen] = useState(false);

    const openModal = () => {
        setIsOpen(true);
    }

    const closeModal = () => {
        setIsOpen(false);
    }

    return (
        <>
            <button onClick={openModal}>Open Modal</button>
            {isOpen && (
                <>
                    <div className="modal-overlay"></div>
                    <div className="modal">
                        <div className="modal-title">{title}</div>
                        <div>
                            {children}
                        </div>
                        <button className="modal-close-button" onClick={closeModal}>X</button>
                    </div>
                </>
            )}
        </>
    );
}

export default ModalPopup;
Create a tab component in React
import React, { useState } from 'react';
import './css/tabs.css';

const Tab = () => {
  const [activeTab, setActiveTab] = useState(1);

  const handleTabClick = (id) => {
    setActiveTab(id);
  };

  return (
    <div>
        <ul className="tabs">
            <li className={activeTab === 1 ? 'active' : ''} onClick={() => handleTabClick(1) }>First Tab</li>
            <li className={activeTab === 2 ? 'active' : ''} onClick={() => handleTabClick(2) }>Second Tab</li>
            <li className={activeTab === 3 ? 'active' : ''} onClick={() => handleTabClick(3) }>Third Tab</li>
            <li className={activeTab === 4 ? 'active' : ''} onClick={() => handleTabClick(4) }>Forth Tab</li>
        </ul>

        <div className="tab_content">
            { activeTab === 1 && <div className="tab_panel">First tab content</div> }
            { activeTab === 2 && <div className="tab_panel">Second tab content</div> }
            { activeTab === 3 && <div className="tab_panel">Third tab content</div> }
            { activeTab === 4 && <div className="tab_panel">Forth tab content</div> }
        </div>
    </div>
  );
};

export default Tab;
Render a string as HTML in React
function app() {
    const html_str = '<h1 style="color:red;">something</h1>';

    return (
        <div dangerouslySetInnerHTML={{ __html: html_str }} />
    );
}
Create a searchable list in React
function App() {
  const myData = ["Apple", "Banana", "Orange", "Papaya", "Grapes"];
  const [filteredData, setFilteredData] = useState(myData);

  function filterData(e) {
    const q = e.target.value.toLowerCase();
    const filteredRecords = myData.filter( item => item.toLowerCase().includes(q) );
    setFilteredData(filteredRecords);
  }

  return (
    <div className="container">
      <div className="search_box">
        <input type="text" onKeyUp={filterData} className="searchCtrl" placeholder="Search the list" />
      </div>
      <div className="box">
        {filteredData && filteredData.length > 0 ? (
          <ul className="list">
            {filteredData.map((item, index) =>
              <li key={index}>{item}</li>
            )}
          </ul>
        ) : <div className="message">Not Data Found</div>
        }
      </div>
    </div>
  );
}
How to Filter an Array of Objects in React
function App() {
  // create an array of objects
  const users = [
    {id: 1, name: 'John', status: 'active'},
    {id: 2, name: 'Rusk', status: 'inactive'},
    {id: 3, name: 'Erlic', status: 'active'},
    {id: 4, name: 'Sara', status: 'active'},
    {id: 5, name: 'Kat', status: 'inactive'}
  ]

  // filter array based on active status
  const filterd_users = users.filter( user => user.status === 'active' );

  return (
    <div>
      <h3>Active Users</h3>
      <ul>
        {filterd_users.map(user =>
          <li key={user.id}>{user.name}</li>
        )}
      </ul>
    </div>
  );
}
Custom Corousal
onScroll = (event) => {
 const activeIndex = Math.round(event.nativeEvent.contentOffset.x / wp(100));
 if (this.state.activeIndex !== activeIndex) {
   this.setState({ activeIndex });
 }
};



<ScrollView
 horizontal={true}
 style={styles.container}
 snapToInterval={wp(100)}
 decelerationRate={0}
 scrollEventThrottle={16}
 onScroll={this.onScroll}
 snapToAlignment={'center'}
 showsHorizontalScrollIndicator={false}>

 </ScrollView>
Upload Image on Ios
const form = new FormData();
await form.append(‘image’, {
name: ‘image’,
type: ‘image/jpeg’,
uri: item
  ? Platform.OS === ‘android’
    ? item
    : item.replace(‘file://‘, ‘’)
  : null,
});
Scroll View Pagination
const scrollX = useRef(new Animated.Value(0)).current;
 
 
<ScrollView
        scrollEnabled={enableScroll}
        horizontal={true}
        pagingEnabled
        showsHorizontalScrollIndicator={false}
        onScroll={Animated.event(
          [
            {
              nativeEvent: {
                contentOffset: {
                  x: scrollX,
                },
              },
            },
          ],
          { useNativeDriver: false },
        )}
        scrollEventThrottle={1}>

</ScrollView>
React Native Modal
import React, {useState} from 'react';
import {Alert, Modal, StyleSheet, Text, Pressable, View} from 'react-native';
 
 
const Modal = () => {
 const [modalVisible, setModalVisible] = useState(true);
 return (
   <Modal
     animationType="slide"
     transparent={true}
     visible={modalVisible}
     onRequestClose={() => {
       Alert.alert('Modal has been closed.');
     }}>
     <View style={styles.centeredView}>
       <View style={styles.modalView} onStartShouldSetResponder={() => true}
>
         <Text style={styles.modalText}>Hello World!</Text>
       </View>
     </View>
</Modal>
 );
};
 
const styles = StyleSheet.create({
 centeredView: {
   flex: 1,
   justifyContent: 'center',
   alignItems: 'center',
   marginTop: 22,
   backgroundColor: 'rgba(0,0,0,0.3)',
 },
 modalView: {
   margin: 20,
   backgroundColor: 'white',
   borderRadius: 20,
   padding: 35,
   alignItems: 'center',
   shadowColor: '#000',
   shadowOffset: {
     width: 0,
     height: 2,
   },
   shadowOpacity: 0.25,
   shadowRadius: 4,
   elevation: 5,
 },
 modalText: {
   marginBottom: 15,
   textAlign: 'center',
 },
});
 
export default Modal;
React Native Map Fit To Cordinates
const MapFitToCordinates = () => {
  map.current.fitToCoordinates(
    [
      {latitude: location.latitude, longitude: location.longitude},
      {latitude: location.latitude, longitude: location.longitude},
    ],
    {
      edgePadding: {
        edgePadding: DEFAULT_PADDING,
        animated: true,
      },
    },
  );
};
Get scrollview active index
const onScroll = (event) => {
  const scrollActiveIndex = Math.round(event.nativeEvent.contentOffset.x / wp(100));
  if (activeIndex !== scrollActiveIndex) {
      setState(scrollActiveIndex)
  }
};
Fetch Data at the end of ScrollView
const isCloseToBottom = ({ layoutMeasurement, contentOffset, contentSize }) => {
  const paddingToBottom = 50;
  return (
    layoutMeasurement.height + contentOffset.y >=
    contentSize.height - paddingToBottom
  );
};





<ScrollView
        style={styles.content}
        showsVerticalScrollIndicator={false}
        onScroll={({ nativeEvent }) => {
          if (isCloseToBottom(nativeEvent) && explore.length % 2 === 0) {
            fetchData();
          }
        }}>
</ScrollView>
Upload Image & File
const form = new FormData();
form.append('image', {
 name: 'image',
 type: 'image/jpeg',
 uri: data.uri,
});
 axios
 .post(`${URL}/api/v1/uploads/image`, form)
 .then(function (response) {
 })
 .catch(function (error) {
   console.log('err', error.response.data);
 });
Highlight the highest value list item using React
function App() {
  // create an array of numbers
  const numbers = [20, 60, 30, 50, 10, 90, 70]

  // Get the index of largest number
  const max_index = numbers.indexOf(Math.max(...numbers));

  return (
    <ul>
        {numbers.map( (item, index) => {
            const hl_class = max_index === index ? 'highlight' : '';

            return <li key={index} className={hl_class}>{item}</li>  
        })}
    </ul>
  );
}
reactjs axios get example
componentDidMount() {
    // Simple PUT request with a JSON body using axios
    const article = { title: 'React PUT Request Example' };
    axios.put('https://reqres.in/api/articles/1', article)
        .then(response => this.setState({ updatedAt: response.data.updatedAt }));
}
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 App() {
  const users = [
    {id: 1, name: 'John'},
    {id: 2, name: 'Rusk'},
    {id: 3, name: 'Erlic'}
  ]

  return (
      <ul>
        {users.map((item, index) =>
          <li key={index}>Index is: {index}. User is {item.name}</li>
        )}
      </ul>
  );
}
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'));