Search code examples
javascripthtmlnode.jsreactjs

How to add HTML component to React.js


App.html

<!DOCTYPE html>
<html>

<head>
    <title>Carousel</title>
    <link rel="stylesheet" type="text/css" href="./css/materialize.min.css">
    </link>
    <link rel="stylesheet" type="text/css" href="App.css">
    </link>
</head>
<div class="carousel">
    <div class="carousel-item">
        <img src={require("./1.png")} class="responsive-img"></img>
    </div>
    <div class="carousel-item">
        <img src={require("./2.png")} class="responsive-img"></img>
    </div>
    <div class="carousel-item">
        <img src={require("./3.png")} class="responsive-img"></img>
    </div>

    <script src="./js/materialize.min.js"></script>

    <script>
        const small = document.querySelector('.carousel');
        var inst = M.Carousel.init(small, {});
        inst.dist(50);
    </script>
</div>

</html>

App.js

import React from 'react';

var perf = require('./App.html');

class App extends React.Component {
   render(){
      return (
        <div dangerouslySetInnerHTML={{ __html: perf }} ></div>
      );
   }
}
export default App;

Can someone please help me with how can I add the HTML file in my JS file and run the HTML file via my JS file. I have made a carousel using materialize in HTML, but I am unable to either write the very code in JS hence, if possible can someone please help me either with converting the HTML file to a JS file, or how can I import the HTML file in my JS file.


Solution

  • Just use react-create-app template and the basic html (head, meta) things are already in place, Just modify the src dir to meet you needs.

    for example the index.js would be something like this,

    import React from 'react';
    import './App.css'; // For Your CSS file
    
    class App extends React.Component {
       render(){
          return (
            <div class="carousel">
        <div class="carousel-item">
            <img src={require("./1.png")} class="responsive-img"></img>
        </div>
        <div class="carousel-item">
            <img src={require("./2.png")} class="responsive-img"></img>
        </div>
        <div class="carousel-item">
            <img src={require("./3.png")} class="responsive-img"></img>
        </div>
          );
       }
    }
    export default App;
    

    if your need to change the base html you can do so in the public dir.

    EDIT: (For the dependencies)

    As you use materialize-css, You can use that by installing materialize-css@next as a dependency using npm with this cmd npm install materialize-css@next

    More info about installing can be found here

    Source: https://materializecss.com/getting-started.html