A tényleges projektek felépítése remek módszer a React elsajátítására és egyes alapelveinek megszilárdítására. Tehát ebben a bejegyzésben egy egyszerű Markdown előnézetet építünk fel, mint amit a fenti képen láthat. Ez egy egyszerű reakció alkalmazás lesz, amely tartalmaz egy szöveget a Markdown bevitelhez és egy előnézeti fület, ahol az átalakított szöveg megjelenik.
Ha közvetlenül a kódba szeretne ugrani, nézze meg a GitHub Repót itt: //github.com/lelouchB/markdown-previewer/tree/master
És itt van egy hivatkozás a telepített verzióra: //markdown-previewer.lelouch-b.now.sh/.
Most kezdjük.
Előfeltételek
- HTML, CSS, Javascript és Bootstrap ismerete.
- A React alapismeretei.
- Csomópont és NPM telepítve a helyi dev gépre.
- Bármely választott kódszerkesztő.
Ha úgy érzi, hogy akadályozza az előrehaladást, mert nem tud eléggé ezekről a témákról, nézze meg a //www.freecodecamp.org/learn oldalt. Van néhány fantasztikus modul, amelyek pillanatok alatt elindítják.
Beállít
Meg fogjuk építeni ezt az alkalmazást a segítségével npx create-react-app
. A React App létrehozása hivatalosan támogatott módszer az egyoldalas React alkalmazások létrehozására . Korszerű felépítést kínál konfiguráció nélkül.
A projektkönyvtárban futtassa a következő parancsot a terminálban:
npx create-react-app markdown-previewer cd markdown-previewer npm start
Ezután nyissa meg a // localhost: 3000 / alkalmazást. Így fog kinézni:

Most nézzük meg a Projekt felépítését itt:
markdown-previewer ├── README.md ├── node_modules ├── package.json ├── .gitignore ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt └── src ├── App.css ├── App.js ├── App.test.js ├── index.css ├── index.js ├── logo.svg └── serviceWorker.js
Nincs konfiguráció vagy bonyolult mappastruktúra - csak az alkalmazás felépítéséhez szükséges fájlok.
Mielőtt tovább folytatnánk, tisztítsuk meg ezeket a fájlokat:
- Törlés
index.css
ésApp.css
. - Mivel töröltük a
index.css
és -tApp.css
, eltávolítunkimport './index.css';
ésimport './App.css';
onnanindex.js
,App.js
illetve. - Törlése
logo.svg
, és távolítsa elimport logo from './logo.svg';
aApp.js
. - Belül
App.js
távolítsa el a funkciótApp()
. Osztálykomponenseket exportálunk, nem pedig funkcionális komponenseket. Tehát változtass,App.js
hogy így nézz ki:
import React from 'react'; export default class App extends React.Component{ render(){ return ( );} }
Menjen át a // localhost: 3000 oldalra, és most üres lesz.
Tervezés
De még egy dolog, mielőtt belemennénk ... Mindig jó ötlet, ha a gépelés megkezdése előtt elkészít egy tervet arról, hogy mit fog építeni. Különösen akkor, ha felhasználói felületet épít a React alkalmazással.
Szeretnénk képet alkotni arról, hogy hogyan fog kinézni a felület, hogy megtudhassuk, milyen összetevőket kell felépítenünk, és az egyes összetevők milyen adatokért felelősek a kezeléséért.
Először is elkészítettem egy gyors vázlatot arról, hogy fog kinézni a markdown-previewer alkalmazás. Címkéztem az összes összetevőt, amelyre szükségünk lesz a létrehozáshoz:

Úgy tűnik tehát, hogy három elsődleges összetevőt kell felépítenünk:
- Cím és alcím - Ez egyszerűen megjeleníti a címsorokat és alcímeket.
- Markdown Input TextArea - Ez az a beviteli texarea, ahova az előnézetben megtekinteni kívánt jelölést írjuk.
- Markdown Preview - Ez egy szürkés hátterű tároló, ahol a kimenet megjelenik.
Néhány megjegyzendő dolog:
- Lesz egy 'App' komponensünk, amely mindent tartalmaz. Ez egy kicsi projekt, így könnyen karbantartható az összes összetevő egyetlen fájlban. A projekt méretének növekedésével (például egy e-kereskedelmi platform építése közben) azonban el kell különítenie az összetevőket különböző fájlokba és mappákba típusaik szerint.
- Mivel ez a cikk nem a CSS-ről és a tervezésről szól, ezért a React-Bootstrap könyvtárat és az Inline Stílusokat fogom használni. A róluk szóló bármilyen vita rövid lesz.
Inline stílusok a React-ben
Az inline stílusok használata azt jelenti, hogy külön CSS fájlok készítése helyett az összetevőket úgy stilizálják, hogy a CSS tulajdonságokat objektumként adják át. Például:
var divStyle = { color: 'white', backgroundImage: 'url(' + imgUrl + ')', WebkitTransition: 'all', // note the capital 'W' here msTransition: 'all' // 'ms' is the only lowercase vendor prefix }; ReactDOM.render( Hello World! , document.getElementById("root");
A stíluskulcsok teve-alapúak, annak érdekében, hogy konzisztensek legyenek a DOM-csomópontok tulajdonságainak JS-től való elérésével (pl node.style.backgroundImage
.). A szállító előtagjai nem ms
nagybetűvel kezdődnek. Ezért WebkitTransition
van nagybetűje "W".
Ezután a stílusobjektum átkerül a DOM komponensbe a használatával {}
. Használhatunk futtatható Javascript kódot a return
módszerünkben a segítségével {}
.
Kód
Oké, itt az ideje elkezdeni a kód írását! Ha bármikor elakad, nyugodtan nézze meg a kész alkalmazást itt: //github.com/lelouchB/markdown-previewer/tree/master és //markdown-previewer.lelouch-b.now.sh/
A függőségek telepítése
Kezdjük a projektfüggőségek telepítésével. A projektkönyvtárban futtassa a következő parancsokat:
npm install react-bootstrap bootstrap npm install marked
Most beszéljük meg őket:
- The first command installs React-Bootstrap and Bootstrap which we will use to style our project.
- The second command installs Marked.js, which is a low-level markdown compiler for parsing markdown without caching or blocking for long periods of time. This will run the actual logic behind converting the markdown.
Before we start using React-Bootstrap inside our project, we will have to add the minified bootstrap CSS file to our index.js
:
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
With this the dependencies have been installed and are ready to be used.
Headings

Our first task will be to add a heading to our React app and center align it. For that we will use Badge, a component of the React-Bootstrap library. Here are the steps to do that:
- Import Badge to
App.js
. InsideApp.js
add the following:
import Badge from "react-bootstrap/Badge";
2. In App.js
inside return and under the div
with the className="App"
, add another div
with the className="container"
.
import React from "react"; import Badge from "react-bootstrap/Badge"; export default class App extends React.Component { render() { return ( ); } }
3. Next inside div with the className="container"
, we will add the heading as follows:
Markdown Previewer
4. You can now see a heading at //localhost:3000, but it is not centered. To center the heading we will use bootstrap and enclose the above code block inside two divs.
Markdown Previewer
With this we have added a heading to our app.
Sub Headings
If you look at the design we're discussing above, you'll see that the next step will be to add two columns with the subheadings Markdown Input and Preview. One will contain the Input TextArea and the other the Preview.
- First we will have to create two columns placed side by side inside our app. We will do so using bootstrap. Inside the div container, add the following:
Lorem Ipsum
Lorem Ipsum
;
I have used Lorem Ipsum for now, and will remove it in the next step. Columns are created using bootstrap classes, and the first div
with className="row mt-4"
creates a row. The m
indicates margin
. The t
indicates top
. The other two div
s with className="col-md-6"
create two columns.
The app will now look something like this.

2. The next step will be to add headings to these columns and center align them. This can be done by adding a div with the className="col text-center" inside that Badge, to both the divs with the className="col-md-6"
.
// Actual Sub Heading: This code block will be same for both columns
3. Your App.js
will now look like this:

TextArea
Next we're going to add a TextArea in our app. We will use the simple HTML tag to do so.
- Add another div with the
classname="mark-input"
and addtextarea
withclassName="input"
inside it.
;
2. Let's customize TextArea a bit. As discussed above, we will be using Inline Styles, so for that let's fist initailize an Object. All the variables will be declared inside the render()
function but outside of return
. For example,
render(){ var variableOne = "Lorem Ipsum" var variableTwo = "Lorem Ipsum" return( // Code ) }
3. Here is the inputStyle
object:
var inputStyle = { width: "400px", height: "50vh", marginLeft: "auto", marginRight: "auto", padding:"10px" };
4. Let's add the inputStyle
object to our textarea
:
With this we have added TextArea to our App and it will look like this:

Preview
To separate our preview from the rest of the app and to enclose it inside a container, we will follow the above process. We'll create a div inside the second columns and add a style object to it, like this:
var outputStyle = { width: "400px", height: "50vh", backgroundColor: "#DCDCDC", marginLeft: "auto", marginRight: "auto", padding:"10px" };
Add the object to the div
:
Preview
Here is how the app will look now:

We now have completed the look of our app, but it is missing its functionality, so let's add that. The process from here can be divided into three steps:
- Taking input from TextArea.
- Passing the input to the Marked.js library and displaying the processed data to the Preview column.
Taking Input from TextArea
We will use the state
object.
State
In React, “state” is an object that represents the parts of the app that can change. Each component can maintain its own state, which lives in an object called this.state
. The state
object is where you store property values that belong to the component.
Simply put, if you’d like your app to do anything – if you want interactivity, adding and deleting things, logging in and out – that will involve state.
Here the value of our textarea is changing, and our state will change with it. We'll add the state object inside our class App, above the render()
function.
It is best practice to initialize state
inside constructor
. It can work without constructor
also but you should avoid that. Here is how we will initialize it with the property markdown
, initially having an empty string:
export default class App extends React.Component { constructor(props){ super(props) this.state = { markdown: "", }; } render(){ // method and other code } }
In this project or in any other react projects, always initialize state
inside constructor(props)
and below super(props)
.
Typically, in React, constructors are only used for two purposes:
- Initializing local state by assigning an object to
this.state
. - Binding event handler methods to an instance.
Keep in mind that Constructor is the only place where you should assign this.state
directly. In all other methods, you need to use this.setState()
instead.
State changes are asynchronous. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
As discussed above we cannot change state directly. Instead we have to use this.setState()
so let's create a method that does that and is called every time the value of textarea is changed.
updateMarkdown(markdown) { this.setState({ markdown }); }
This method is created inside the class component but above the render()
function.
But we will first set the value of textarea to the markdown
property in state.
Now we can add updateMarkdown()
to onChange()
event inside and call it
this.updateMarkdown()
.
{ this.updateMarkdown(e.target.value); }} >;
Next we can check to see if state is assigning properly by passing a Javascript code and console.log()
our state.
{ this.updateMarkdown(e.target.value); }} > {console.log(this.state.markdown)} ;
Now open your console and try writing inside textarea, and hopefully you will see the same being added to the console.

With this we have successfully assigned the input of textarea to our state markdown property. Here is how your App.js
will look now:
Marked.js
Marked.js is the brains behind the conversion of markdown and is very simple to use.
Importing marked
, add the following just below where you imported Badge from react-bootstrap/Badge
let marked = require("marked");
To use the Marked.js library, we just have to pass the string to be converted inside the marked()
function. We already have the data dynamically stored inside the state object, so it will be done like this:
marked(this.state.markdown)
Most a következő lépés az átalakított adatok tényleges megjelenítése a weboldalon. Ehhez dangerouslySetInnerHTML
a React DOM elemei alatt található attribútumot fogjuk használni . A hivatalos dokumentáció szerint:
dangerouslySetInnerHTML
a React helyettesíti
innerHTML
a böngésző DOM használatát.
Ez azt jelenti, hogy ha a React-ben programozva vagy külső forrásból kell beállítania a HTML-t , akkor a Javascriptben dangerouslySetInnerHTML
a hagyományos helyett kell használnia innerHTML
.
Egyszerű szavakkal a dangerouslySetInnerHTML
HTML-t közvetlenül a React-ből állíthatja be.
Használat közben dangerouslySetInnerHTML
át kell adnia egy objektumot egy __html
kulccsal. (Vegye figyelembe, hogy a kulcs két aláhúzásból áll.)
Így fogjuk ezt megtenni:
With this we have completed our project and now you will see your Markdown Previewer
in action.
Here is the complete App.js
We did it! ?
Congrats on building this React Mardown Previewer.
What next?
So, what is the future of this project? You are the future. Make your own version of Markdown Previewer, add different designs, layouts, custom functionalities. For example you could add a Reset Button to clear the textarea – it's all up to your imagination. I hope you had fun coding along.
What other projects or tutorials would you like to see ? Reach out to me on Twitter, and I'll make more tutorials! If you're inspired to add features yourself, please do share and tag me – I'd love to hear about them :)