Categories
React Answers

How to invoke link click via button press in React?

Sometimes, we want to invoke link click via button press in React.

In this article, we’ll look at how to invoke link click via button press in React.

How to invoke link click via button press in React?

To invoke link click via button press in React, we can set the window.location.href property to the string of the URL that we want to go to.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <div>
      <button
        type="button"
        onClick={(e) => {
          e.preventDefault();
          window.location.href = "https://example.com";
        }}
      >
        Click here
      </button>
    </div>
  );
}

to set the onClick prop of the button to a function that goes to https://example.com when we click the button.

We do this by setting window.location.href to "https://example.com".

Conclusion

To invoke link click via button press in React, we can set the window.location.href property to the string of the URL that we want to go to.

Categories
React Answers

How to change color of react-big-calendar events?

Sometimes, we want to change color of react-big-calendar events.

In this article, we’ll look at to change color of react-big-calendar events.

How to change color of react-big-calendar events?

To change color of react-big-calendar events, we can set the eventPropGetter prop to a function that returns an object with the style property.

For instance, we write:

import React from "react";
import { Calendar, momentLocalizer } from "react-big-calendar";
import "react-big-calendar/lib/css/react-big-calendar.css";
import moment from "moment";

const localizer = momentLocalizer(moment);

const myEventsList = [
  {
    start: moment().toDate(),
    end: moment().add(1, "days").toDate(),
    title: "Some title"
  }
];

export default function App() {
  return (
    <div>
      <Calendar
        localizer={localizer}
        events={myEventsList}
        startAccessor="start"
        endAccessor="end"
        style={{ height: 500 }}
        eventPropGetter={(event, start, end, isSelected) => ({
          event,
          start,
          end,
          isSelected,
          style: { backgroundColor: "green" }
        })}
      />
    </div>
  );
}

We add the Calendar component and set the eventPropGetter prop to a function that returns an object with the style prop set to an object with the styles added.

And we return all the parameter values in the same object to keep the event data.

We populate the event with the events prop.

And we set startAccessor to the 'start' property and endAccessor to the 'end' property of the event objects in myEventList.

Finally, we set the events prop to myEventList to populate the calendar with the events in the array.

Conclusion

To change color of react-big-calendar events, we can set the eventPropGetter prop to a function that returns an object with the style property.

Categories
React Answers

How to use the media query syntax in React component?

Sometimes, we want to use the media query syntax in React component.

In this article, we’ll look at how to use the media query syntax in React component.

How to use the media query syntax in React component?

To use the media query syntax in React component, we can use the window.matchMedia method.

For instance, we write:

import React, { useState, useEffect } from "react";

export default function App() {
  const [isDesktop, setDesktop] = useState(
    window.matchMedia("(min-width: 650px)").matches
  );

  const updateMedia = () => {
    setDesktop(window.matchMedia("(min-width: 650px)").matches);
  };

  useEffect(() => {
    window.addEventListener("resize", updateMedia);
    return () => window.removeEventListener("resize", updateMedia);
  });

  return (
    <div>
      {isDesktop ? (
        <div>I show on 651px or higher</div>
      ) : (
        <div>I show on 650px or lower</div>
      )}
    </div>
  );
}

We create the isDesktop state which is set to window.matchMedia("(min-width: 650px)").matches initially.

We call window.matchMedia with a string that has CSS media queries to check if the screen’s width is 650px or wider.

Then we define the updateMedia function that calls setDesktop with window.matchMedia("(min-width: 650px)").matches.

Then we call useEffect with a callback that attaches the resize event listener to window with addEventListener.

We use updateMedia as the resize event listener.

In updateMedia, we call setDesktop with window.innerWidth > 650 to check if we’re in a desktop sized screen.

Also, we return a function to calls window.removeEventListener to clear the event listener.

Finally, we render the content we want based on the value of isDesktop.

Conclusion

To use the media query syntax in React component, we can use the window.matchMedia method.

Categories
React Answers

How to conditionally render items based on viewport size in React?

Sometimes, we want to conditionally render items based on viewport size in React.

In this article, we’ll look at how to conditionally render items based on viewport size in React.

How to conditionally render items based on viewport size in React?

To conditionally render items based on viewport size in React, we can listen to the resize event emitted by window.

For instance, we write:

import React, { useState, useEffect } from "react";

export default function App() {
  const [isDesktop, setDesktop] = useState(window.innerWidth > 650);

  const updateMedia = () => {
    setDesktop(window.innerWidth > 650);
  };

  useEffect(() => {
    window.addEventListener("resize", updateMedia);
    return () => window.removeEventListener("resize", updateMedia);
  });

  return (
    <div>
      {isDesktop ? (
        <div>I show on 651px or higher</div>
      ) : (
        <div>I show on 650px or lower</div>
      )}
    </div>
  );
}

We create the isDesktop state which is set to window.innerWidth > 650 initially.

Then we define the updateMedia function that calls setDesktop with window.innerWidth > 650.

Then we call useEffect with a callback that attaches the resize event listener to window with addEventListener.

We use updateMedia as the resize event listener.

In updateMedia, we call setDesktop with window.innerWidth > 650 to check if we’re in a desktop sized screen.

Also, we return a function to calls window.removeEventListener to clear the event listener.

Finally, we render the content we want based on the value of isDesktop.

Conclusion

To conditionally render items based on viewport size in React, we can listen to the resize event emitted by window.

Categories
React Answers

How to print a React component on click of a button?

Sometimes, we want to print a React component on click of a button.

In this article, we’ll look at how to print a React component on click of a button.

How to print a React component on click of a button?

To print a React component on click of a button, we can use the react-to-print library.

To install it, we run:

npm i react-to-print

Then we write:

import React, { forwardRef, useRef } from "react";
import ReactToPrint, { PrintContextConsumer } from "react-to-print";

const ComponentToPrint = forwardRef((props, ref) => {
  return <div ref={ref}>hello world</div>;
});

export default function App() {
  const ref = useRef();

  return (
    <div>
      <ReactToPrint content={() => ref.current}>
        <PrintContextConsumer>
          {({ handlePrint }) => (
            <button onClick={handlePrint}>Print this out!</button>
          )}
        </PrintContextConsumer>
      </ReactToPrint>
      <ComponentToPrint ref={ref} />
    </div>
  );
}

to use it.

We wrap the component that triggers the opening of the print dialog in the PrintContextConsumer.

And we wrap the PrintContextConsumer with the ReactToPrint component.

We set the content prop to a function that returns the ref.current value of the component we want to print when we click on the button.

We make the button open the print dialog by setting onClick to handlePrint.

Next, we set the ref prop of the element we want to print as the value of the ref prop.

Conclusion

To print a React component on click of a button, we can use the react-to-print library.