Custom Styled Input field in react js - html

I am looking for input field which take the input in formated way based on user selection of font, bullets and code type.
Provided the image below
Code should be in React Js and output can be html in json format

You're trying to say you need to implement a rich text editor using React?
Well, in that case I personally use jodit-react because it's open-source, works well with TypeScript and NextJS and outputs the text in HTML format. You can find the project here and basic implementation looks like this.
import React, {useState, useRef, useMemo} from 'react';
import JoditEditor from "jodit-react";
const Example = ({placeholder}) => {
const editor = useRef(null)
const [content, setContent] = useState('')
const config = useMemo({
readonly: false // all options from https://xdsoft.net/jodit/doc/,
placeholder: placeholder || 'Start typing...'
},
[placeholder])
return (
<JoditEditor
ref={editor}
value={content}
config={config}
tabIndex={1} // tabIndex of textarea
onBlur={newContent => setContent(newContent)} // preferred to use only this option to update the content for performance reasons
onChange={newContent => {}}
/>
);
}
Take a look at this example below.
Hope this helps!
Cheers!

Related

Conditionally make a page read-only using react

I want to create a React webpage that has both editable and read-only versions, the whole page not just a few elements on the page. A version is displayed to the user based on user id and other conditions. How do I do it?
The only straight forward way I know is to create 2 pages one editable and one read-only and based on the condition show the appropriate version (html page) to the user.
Is there a better and smarter way to do this? Like can I create just one page for both versions and toggle the mode based on the condition to the users?
Your question should have provided an example of some code you had tried but based on the description, very rough example below of one of many possible solutions.
Suppose EditView component is your page and you are able to pass a value for permission based on whatever credential you need to apply.
Then you have a component, ExampleField that takes the permission and displays either an input or static text. A collection of multiple of these fields is mapped from a theoretical array of data that you'll have to fetch from somewhere and the fields are returned by the main component.
const EditView = ({permission}) => {
const [editable, setEditable] = useState();
const [values, setValues] = useState([]);
useEffect(() => {
setEditable(permission);
}, [permission]);
useEffect(() => {
//maybe fetch your data from a back end or whatever and assign it to `values`
//on page load
}, [])
const ExampleField = ({permission, val, index}) => {
const handleChange = (e) => {
let vals = [...values];
vals[index] = val;
setValues(vals);
}
return(
<>
{permission
? <input name="example" type="text" defaultValue={val}
onChange={handleChange} />
: <span>{val}</span>}
</>
)
}
const fields = values.map((value, i) => {
return <ExampleField permission={permission} val={value} index={i}/>
})
return(
<>
{fields}
</>
)
}
Most likely, you'll want to break out various field components into their own file and, instead of using useState, you would probably want to explore useContext or useStore type functionality to lift up your state and do all the react things.
*Haven't tested or even compiled this code - for illustration purposes only.

I am displaying dynamic data on this React Boostrap Slider. Is there a way to make the code more efficient?

this is my first post here. I am building a React Boostrap Carousel that pulls Movie data from the database and displays it. I am new to React and programming in general. So far i made the code work. But i do not know how to handle the images. The images are stores in React **src/assets/imgs. **. Should i store a reference to the image in the database like so ../../assets/imgs/the-batman.jpg and then display it? If so later on on the project the admin will have to create a MovieOfTheMonth. He should be able to input movie title, descrition etc, and also upload a movie image. Is there a way when the image is uploaded it, to store it to a specific folder, in this case src/assets/imgs and also create a reference in the database? I do not need the solution here, just to tell me if it is achievable. Finally is there a way to improve my code?
this is my full code for this component
import React, {useState, useEffect } from 'react';
import './Carousel.css'
import Carousel from 'react-bootstrap/Carousel';
import 'bootstrap/dist/css/bootstrap.min.css';
import axios from 'axios';
const CarouselHero = () => {
//boostrap code
const [index, setIndex] = useState(0);
const handleSelect = (selectedIndex, e) => {
setIndex(selectedIndex);
};
//Get Movies of the month
const [movie, setMovie] = useState([])
const getMovie = () => {
axios.get("http://localhost:4000/moviesOfTheMonth")
.then((res) => {
const myMovie = res.data
myMovie.push()
setMovie(myMovie);
})
}
useEffect(() => getMovie(), []);
return (
<Carousel activeIndex={index} onSelect={handleSelect} fade>
{movie.map((item) => {
const {id, title, description} = item.Movie
return (
<Carousel.Item interval={2000}>
<img
src={require("../../assets/imgs/the-batman.jpg")}
alt="First slide"
/>
<Carousel.Caption >
<h1>{title}</h1>
<p>{description}</p>
<button>Book Now</button>
</Carousel.Caption>
</Carousel.Item>
)
})}
</Carousel>
);
};
export default CarouselHero;
I think technically it is achievable to iterate over the assets folder and create database entries for new images (create and compare hash?), but it is usually not how you do it. I would put images in some file storage like S3 and reference them with id.
I don't know who the admin will be in your project, but if admin is rather a non technical person, you could create (or use a template of course) a small and simple admin dashboard, where he/she can maintain a movie of the month via UI.
FFinally some remarks on your code:
const handleSelect = (selectedIndex, e) => { setIndex(selectedIndex); }; - If you need only first, but not second, third etc. argument, you can just leave it out: (selectedIndex) => ...
const [movie, setMovie] = useState([]) - don't forget to use semicolon after every statement. (They are optional, but are useful sometimes to avoid weird errors). Also, you have a list here. So maybe better call it "movies".
myMovie.push() - What are you trying to push here?
useEffect(() => getMovie(), []); - Usually you define and call async function directly in useEffect. Don't you get any hints or warning?
movie.map((item) => { - When you iterate and get a list back React needs a key on every element (here on Carousel.Item). Don't just use the index, as it is a bad practice. Always try to find id property in your data.
const {id, title, description} = item.Movie - Why is the data nested by Movie object? Can't you just say item.id, item.title, item.description?

How to bind value to be displayed in html in React?

I just created my first test in React.
Following an example of a tutorial I have created several buttons that activate a function by which they receive the index of the selected button. The first button selected must show one of the operators of the aray and the next one the opposite, and so on...
const operators = ['+', '-'];
const placeHolder = 'o';
function Boxes(props){
return (
<AppContext.Consumer>
{context => {
const value = context.boxes[props.index];
const icon = value !== null ? operators[value] : placeHolder;
const isDone = icon !== placeHolder ? 'done' : '';
return (
<button className="box-active"
onClick={() => context.boxAct(props.index)}>
{operator}
</button>
)
}}
</AppContext.Consumer>
)
}
and here is de function
boxAct = (index) => {
if (this.state.boxes[index] === null) {
this.state.boxes[index] = '+';
}
}
How can I achieve this? Following the steps of the example I only get the placeholder value in all the buttons and I can't get them to change.
What am I doing wrong?
thanks for your help
Functional components are different from class components. As you can read from official documentation react components.
Your Boxes component is declared as functional component. this.state syntax is valid just inside class component. In that case correct way to update state would be to call this.setState(<newstate>) function avilable to all class components. You can read more here react state.
You can provide state to functional components via hooks. In particolar useState hook. Here is explained how to do useState hook.
In your case (functional component) you can dop like this:
import hook with:
import React, { useState } from 'react';
then you need to initialize boxes state like this
const [boxes, setBoxes] = useState(context.boxes)
The function you will set as onClick handler is:
boxAct = (index) => { if (boxes[index] === null) {
let newBoxes = boxes;
nexBoxes[index] = '+';
setBoxes(newBoxes);
}
}
Be aware also that you should not pass data via context api, context api is used to provide global information such as application language or theme. Read more here react context

What is the difference between document.createElement('div') and React.createElement('div')?

str = "<p> this is paragraph </p>"
The above str can consist of any elements of HTML. So to get he text I have used the below code in my react application.
let descriptionDiv = document.createElement('div');
descriptionDiv.innerHTML = description;
description = descriptionDiv.textContent || descriptionDiv.innerText;
Do I need to use ReactDOM in this scenario ?
Like: React.createElement('div');
But I don't know whether when to use it ? Is it safe to accessing dom directly?
JSX elements will be transpiled to React.createElement() functions to create React elements which are going to be used for the object representation of UI
In html it's just creating another node to dom.
If you want to access dom while using react you can use ref
To access the DOM pass a ref with the react element and latter access it with findDOMNode method
It's completely safe to use dom api directly but it depends what is your requirement... simple or you have some complicated tasks ,prefer to use ref in react
example
import ReactDOM from 'react-dom';
...
let reactElement = ReactDOM.findDOMNode(this.refs.refName)
...
<Component ref='refName'/>
React.createElement
React.createElement(
"button",
{
className: "panel-btn-open"
},
"Open"
),
document.createElement
const buttonOpen = document.createElement('button');
buttonOpen.classList.add('panel-btn-open');
buttonOpen.textContent = 'Open';

Render React Native Elements from JSON

I have searched around...can't quite find what I'm looking for, so I appreciate any help! Here is what I am going for:
I am building a CMS-like setup for a React Native app. This is so that an admin of an app can login to the CMS dashboard, and update a page/view of the app without having to go into the hardcode. I would like them to be able to choose from a pre-set list of components and be able to drag-and-drop them into the app, in whatever order they would want and be able to update the content and colors, etc. Let me provide an example...
There is a home page that I imagine having a rotating banner at the top, then a button for a information modal, then a set of menu links to go to sub-child pages.
So what I think, development-wise, is to give the app admin a WYSIWYG type of setup, and to store the result of this in the Database. It could store in the database as:
<RotatingBanner />
<Modal />
<ContentMenu>
<ContentMenuLink title="About" />
<ContentMenuLink title="Competitive" />
<ContentMenuLink title="Recreational" />
<ContentMenuLink title="Tournaments" />
<ContentMenu />
Right now, when I try to render this into a screen, I continue to have it render that as the actual words vs the components they are representing if that makes sense. So the page looks just like the code block above, instead of seeing a rotating banner and modal, etc.
I have tried a tool to convert HTML into React Native elements...does anyone know how I can convert a fetched JSON that would look like:
{content: "<RotatingBanner /><Modal /><ContentMenu>...."}
and have it create the real components in the render function? Any other thoughts or ideas/advice on creating a CMS like this are greatly appreciated if you would like.
Thanks!
Let's say your have this JSON:
const data = {
"components": [
{"name": "component1", props: {"hello": "world"}},
{"name": "component2", props: {"color": "red"}},
]
}
Make your components and then reference them in an Object (map):
import Component1 from './Component1'
import Component2 from './Component2'
const COMPONENT_MAP = {
component1: Component1,
component2: Component2,
}
Then make your wrapper component:
const Wrapper = ({data}) => (
<View>
{data.components.map(({name, props}) => {
const Component = COMPONENT_MAP[name]
return <Component {...props} />
}}
</View>
)
VoilĂ  :)
<Wrapper data={data} />
I would recommend using Array's to save and render multiple childrens
const Component1 = () => <Text>One</Text>
const Component2 = () => <Text>One</Text>
const childs = [
Component1,
Component2
]
return childs
React is able to render arrays as they are.
Other possible solution could be,
return Object.keys(child).map(item => childs[item] )
A quick solution can be react-native-dynamic-render
Also, you can render nested components with that.
A complete example is here