Categories
React Answers

How to hold file input’s value in React?

Sometimes, we want to hold file input’s value in React.

In this article, we’ll look at how to hold file input’s value in React.

How to hold file input’s value in React?

To hold file input’s value in React, we can store the selected file in a state.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [file, setFile] = useState();

  const handleChange = (e) => {
    const [f] = e.target.files;
    setFile(f);
  };

  console.log(file);

  return (
    <div>
      <input onChange={handleChange} multiple={false} type="file" />
    </div>
  );
}

We create the file state with the useState hook.

Then we add the handleChange function that gets the selected file from the e.target.files file list object property.

Then we call setFile with f to set f as file‘s value.

Now when we select a file, we should see file‘s value logged in the console log.

Conclusion

To hold file input’s value in React, we can store the selected file in a state.

Categories
React Answers

How to read and upload a file in React using custom button?

Sometimes, we want to read and upload a file in React using custom button.

In this article, we’ll look at how to read and upload a file in React using custom button.

How to read and upload a file in React using custom button?

To read and upload a file in React using custom button, we can add a hidden file input.

Then we can add a click handler for the button to open the file input.

For instance, we write:

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

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

  const handleChange = (e) => {
    const [file] = e.target.files;
    console.log(file);
  };

  return (
    <div>
      <button onClick={() => fileRef.current.click()}>
        Custom File Input Button
      </button>
      <input
        ref={fileRef}
        onChange={handleChange}
        multiple={false}
        type="file"
        hidden
      />
    </div>
  );
}

to create a ref with the useRef hook.

Then we add a button and a file input.

We assign fileRef to the file input by setting it as the value of the ref prop.

We add the hidden prop to the input to hide it.

Next, we set the onClick prop of the button to a function that calls fileRef.current.click to open the file selector dialog when we click on it.

Conclusion

To read and upload a file in React using custom button, we can add a hidden file input.

Then we can add a click handler for the button to open the file input.

Categories
React Answers

How to use the chart tooltip formatter in react-highcharts?

Sometimes, we want to use the chart tooltip formatter in react-highcharts.

In this article, we’ll look at how to use the chart tooltip formatter in react-highcharts.

How to use the chart tooltip formatter in react-highcharts?

To use the chart tooltip formatter in react-highcharts, we can set the tooltip.formatter property to a function that returns the tooltip text.

For instance, we write:

import React from "react";
import ReactHighcharts from "react-highcharts";

const config = {
  xAxis: {
    categories: ["Jan", "Feb", "Mar", "Apr", "May"]
  },
  tooltip: {
    formatter() {
      let s = `<b>${this.x}</b>`;
      this.points.forEach(
        (point) => (s += `<br/>${point.series.name}: ${point.y}m`)
      );

      return s;
    },
    shared: true
  },
  series: [
    {
      data: [29.9, 71.5, 106.4, 129.2, 144.0]
    },
    {
      data: [194.1, 95.6, 54.4, 29.9, 71.5]
    }
  ]
};

export default function App() {
  return (
    <div>
      <ReactHighcharts config={config} />
    </div>
  );
}

We define the config object to store the config for the chart.

The series property defines the series data.

xAxis defines the x-axis texts.

And the tooltip.formatter method returns the text for each tooltip.

We get the x coordinate value for the point with this.x.

And this.points has the points’ data.

point.series.name has the series name. And point.y has the y-coordinate value.

Conclusion

To use the chart tooltip formatter in react-highcharts, we can set the tooltip.formatter property to a function that returns the tooltip text.

Categories
React Answers

How to filter out null children values with React?

Sometimes, we want to filter out null children values with React.

In this article, we’ll look at how to filter out null children values with React.

How to filter out null children values with React?

To filter out null children values with React, we can use the React.Children.toArray method to convert the children prop to an array.

Then we can use the array’s filter method to filter out the null values.

For instance, we write:

import React from "react";

const MyComponent = ({ children }) => {
  const c = React.Children.toArray(children).filter(Boolean);

  return <div>{c}</div>;
};

export default function App() {
  return (
    <div>
      <MyComponent>
        <p>foo</p> {null} <p>bar</p>
      </MyComponent>
    </div>
  );
}

to define the MyComponent component that takes the children prop.

And in it, we call React.Children.toArray with children to convert the children prop object to an array.

Then we call filter to return a new array without the null values.

Finally, in App, we add the items in between the MyComponent tags.

And we can see that only the p elements are rendered.

Conclusion

To filter out null children values with React, we can use the React.Children.toArray method to convert the children prop to an array.

Then we can use the array’s filter method to filter out the null values.

Categories
React Answers

How to display PDF in React?

Sometimes, we want to display PDF in React.

In this article, we’ll look at how to display PDF in React.

How to display PDF in React?

To display PDF in React, we can use the react-pdf library.

To add it, we run:

npm i react-pdf

Then we can use it by writing:

import React, { useState } from "react";
import { Document, Page, pdfjs } from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;

export default function App() {
  const [numPages, setNumPages] = useState(null);
  const [pageNumber] = useState(1);

  const onDocumentLoadSuccess = ({ numPages }) => {
    setNumPages(numPages);
  };

  return (
    <div>
      <Document
        file="https://www.jianjunchen.com/papers/CORS-USESEC18.slides.pdf"
        onLoadSuccess={onDocumentLoadSuccess}
      >
        <Page pageNumber={pageNumber} />
      </Document>
      <p>
        Page {pageNumber} of {numPages}
      </p>
    </div>
  );
}

We set the pdfjs.GlobalWorkerOptions.workerSrc to the URL of the pdf.js worker used to load the PDF.

Then we use the Document component with the file prop set the URL of the PDF.

The onLoadSuccess prop is set to the onDocumentLoadSuccess function which takes an object with the numPage property so we know how many pages the loaded PDF has.

Then we can use the Page component to load the pages.

We should see the PDF’s first page displayed if we load the PDF from our own domain or from a server that has CORS enabled.

Conclusion

To display PDF in React, we can use the react-pdf library.