React - How to return HTML elements in JSON
Asked Answered
J

6

9

I have a JSON file that contains HTML elements in a string - Is it possible to return the data in React/JSX as valid rendered HTML?

var Hello = React.createClass({
  render: function() {
    var exampleJSONData = {
        "item": "Hello",
        "text": "<p>Lorem ipsum</p><p>dolor sit amet</p>"
    }
    return <div>{data.item} {data.text}</div>;
  }
});

Returns : Hello <p>Lorem ipsum</p><p>dolor sit amet</p> instead of:

Hello
Lorem ipsum
dolor sit amet

fiddle

Joijoice answered 28/1, 2016 at 6:21 Comment(0)
C
19

You can try use dangerouslySetInnerHTML like this

<div dangerouslySetInnerHTML={ {__html: data.text} } />

Example

Clemons answered 28/1, 2016 at 6:25 Comment(1)
Thanks, I had forgotten about this dangerouslySetInnerHTMLHypoxia
F
0
import React, { useState } from 'react';

const TextAreaExample = () => {
    const [inputText, setInputText] = useState('');
    const [displayText, setDisplayText] = useState('');

    const handleChange = (e) => {
        setInputText(e.target.value);
    };

    const handleSubmit = () => {
        setDisplayText(inputText);
    };

    return (
        <div>
            <textarea
                rows="5"
                cols="50"
                value={inputText}
                onChange={handleChange}
                placeholder="Enter text here..."
            ></textarea>
            <br />
            <button onClick={handleSubmit}>Submit</button>
            <br /><br />
            {displayText && <h4>{displayText}</h4>}
        </div>
    );
};

export default TextAreaExample;
Flagellate answered 26/6 at 7:36 Comment(1)
I appreciate your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that the community has extensively validated. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to explain?Soileau
F
0

Sure, I'll help you create a popup modal in React that displays options for different templates. When a template is clicked, the selected template will be processed accordingly. Here's a basic example using React and some CSS for the modal:

React Code

  1. Install Dependencies:

If you're not already using a UI library, you might want to install react-modal for creating modals easily:

npm install react-modal
  1. App Component:

Here is an example of the main application component:

import React, { useState } from 'react';
import Modal from 'react-modal';
import './App.css';

const templates = [
    { id: 1, name: 'Template 1' },
    { id: 2, name: 'Template 2' },
    { id: 3, name: 'Template 3' },
    { id: 4, name: 'Template 4' },
    { id: 5, name: 'Template 5' },
];

const App = () => {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [selectedTemplate, setSelectedTemplate] = useState(null);

    const openModal = () => {
        setIsModalOpen(true);
    };

    const closeModal = () => {
        setIsModalOpen(false);
    };

    const handleTemplateSelect = (template) => {
        setSelectedTemplate(template);
        closeModal();
        // Handle template selection (e.g., add nodes)
        console.log(`Selected Template: ${template.name}`);
    };

    return (
        <div className="App">
            <button onClick={openModal}>Use Existing Template</button>
            <Modal
                isOpen={isModalOpen}
                onRequestClose={closeModal}
                contentLabel="Select a Template"
                className="Modal"
                overlayClassName="Overlay"
            >
                <h2>Select a Template</h2>
                <ul>
                    {templates.map((template) => (
                        <li key={template.id} onClick={() => handleTemplateSelect(template)}>
                            {template.name}
                        </li>
                    ))}
                </ul>
                <button onClick={closeModal}>Close</button>
            </Modal>
        </div>
    );
};

export default App;
  1. CSS (App.css):

Add some basic styles for the modal:

/* App.css */
.Modal {
    position: absolute;
    top: 50%;
    left: 50%;
    right: auto;
    bottom: auto;
    marginRight: -50%;
    transform: translate(-50%, -50%);
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.Overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    backgroundColor: rgba(0, 0, 0, 0.5);
}

ul {
    list-style: none;
    padding: 0;
}

li {
    padding: 10px;
    margin: 5px 0;
    cursor: pointer;
    background-color: #f0f0f0;
    border-radius: 5px;
}

li:hover {
    background-color: #ddd;
}

button {
    padding: 10px 20px;
    margin-top: 20px;
}

Explanation

  • Modal Component: The react-modal package is used to create the modal. The modal contains a list of templates.
  • Button: A button to open the modal.
  • List of Templates: When a template is clicked, it sets the selected template and closes the modal.
  • CSS: Some basic styles for the modal and the list of templates.

You can now integrate this code into your existing React project. The handleTemplateSelect function can be extended to add the nodes belonging to the selected template.

Flagellate answered 3/7 at 10:0 Comment(0)
F
0

Sure, I can help you build a drop-down component using React and Redux. Here’s a step-by-step guide:

1. Set Up Your Redux Store

First, ensure you have the necessary packages installed:

npm install redux react-redux @reduxjs/toolkit

2. Create Redux Slice for Events

Create a slice to manage the events state.

// src/features/events/eventsSlice.js
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

export const fetchEvents = createAsyncThunk('events/fetchEvents', async () => {
  const response = await axios.get('/api/events');  // Adjust the URL to your API endpoint
  return response.data;
});

const eventsSlice = createSlice({
  name: 'events',
  initialState: {
    events: [],
    status: 'idle',
    error: null
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchEvents.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchEvents.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.events = action.payload;
      })
      .addCase(fetchEvents.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message;
      });
  }
});

export default eventsSlice.reducer;

3. Configure the Store

Configure the Redux store to include the events slice.

// src/app/store.js
import { configureStore } from '@reduxjs/toolkit';
import eventsReducer from '../features/events/eventsSlice';

export const store = configureStore({
  reducer: {
    events: eventsReducer
  }
});

4. Provide the Store

Wrap your application with the Redux Provider.

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './app/store';
import App from './App';

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

5. Create the Drop-down Component

Create a drop-down component that uses the events state from Redux.

// src/components/Dropdown.js
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchEvents } from '../features/events/eventsSlice';

const Dropdown = () => {
  const dispatch = useDispatch();
  const events = useSelector((state) => state.events.events);
  const eventStatus = useSelector((state) => state.events.status);
  const error = useSelector((state) => state.events.error);

  useEffect(() => {
    if (eventStatus === 'idle') {
      dispatch(fetchEvents());
    }
  }, [eventStatus, dispatch]);

  let content;

  if (eventStatus === 'loading') {
    content = <option>Loading...</option>;
  } else if (eventStatus === 'succeeded') {
    content = events.map((event) => (
      <option key={event.id} value={event.id}>
        {event.name}
      </option>
    ));
  } else if (eventStatus === 'failed') {
    content = <option>Error: {error}</option>;
  }

  return (
    <select>
      <option value="">Select an event</option>
      {content}
    </select>
  );
};

export default Dropdown;

6. Use the Drop-down Component

Include the Dropdown component in your main application or wherever needed.

// src/App.js
import React from 'react';
import Dropdown from './components/Dropdown';

const App = () => {
  return (
    <div>
      <h1>Event Dropdown</h1>
      <Dropdown />
    </div>
  );
};

export default App;

This setup ensures your drop-down component fetches the events from an API and displays them. React-Redux handles the state management efficiently, and your component stays clean and focused on rendering the UI.

Flagellate answered 29/7 at 11:41 Comment(0)
F
-1

import React, { useState } from 'react'; import { Handle, Position } from 'reactflow';

const CustomNode = ({ data, isConnectable }) => { const [formData, setFormData] = useState(data.curComp.mappingConfig);

const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevData) => ({
        ...prevData,
        [name]: value,
    }));
};

const handleSubmit = (e) => {
    e.preventDefault();
    document.getElementById('jsonOutput').innerText = JSON.stringify(formData, null, 2);
};

const renderFormFields = (obj) => {
    return Object.keys(obj).map((key) => {
        if (typeof obj[key] === 'object') {
            return (
                <div key={key}>
                    <label>{key}:</label>
                    <div style={{ marginLeft: '20px' }}>
                        {renderFormFields(obj[key])}
                    </div>
                </div>
            );
        }
        return (
            <div key={key}>
                <label htmlFor={key}>{key}:</label>
                <input
                    type="text"
                    id={key}
                    name={key}
                    value={obj[key]}
                    onChange={handleChange}
                />
                <br /><br />
            </div>
        );
    });
};

return (
    <div className="text-updater-node">
        <Handle type="target" position={Position.Top} isConnectable={isConnectable} />
        <form id="dataForm" onSubmit={handleSubmit}>
            {renderFormFields(formData)}
            <button type="submit">Submit</button>
        </form>
        <div id="jsonOutput" style={{ whiteSpace: 'pre-wrap', marginTop: '10px', padding: '10px', border: '1px solid #ddd', borderRadius: '5px' }}></div>
        <Handle type="source" position={Position.Bottom} id="b" isConnectable={isConnectable} />
    </div>
);

};

export default CustomNode;

Flagellate answered 25/6 at 10:59 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Lynnette
F
-1

import React, { useState } from 'react';

const json = { "type": "REST", "bosellr1": "POA_RAAS_ROS_BASEURL", "endpoint": "/getAccountDetails", "httpMethod": "POST", "auth": { "type": "IDA", "resourceId": "POA_RAAS_ROS_RESOURCE_URI" }, "responseValidationFields": [ "enquiryResponse.accountDetailResponselist[0].account.accountStatusCO", "enquiryResponse.accountDetailResponselist[1].account.deaccount", "ddaAccountStatusCD" ] };

const DynamicForm = ({ data }) => { const [formData, setFormData] = useState(data);

const handleChange = (path, value) => {
    const updateFormData = (obj, path, value) => {
        const keys = path.split('.');
        const lastKey = keys.pop();
        const deepObj = keys.reduce((acc, key) => acc[key], obj);
        deepObj[lastKey] = value;
    };

    const updatedData = { ...formData };
    updateFormData(updatedData, path, value);
    setFormData(updatedData);
};

const renderFormFields = (obj, path = '') => {
    return Object.keys(obj).map((key) => {
        const newPath = path ? `${path}.${key}` : key;
        if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
            return (
                <div key={newPath} style={{ marginLeft: '20px' }}>
                    <label>{key}:</label>
                    {renderFormFields(obj[key], newPath)}
                </div>
            );
        } else if (Array.isArray(obj[key])) {
            return (
                <div key={newPath}>
                    <label>{key}:</label>
                    <div style={{ marginLeft: '20px' }}>
                        {obj[key].map((item, index) => (
                            <div key={`${newPath}[${index}]`}>
                                <input
                                    type="text"
                                    value={item}
                                    onChange={(e) => handleChange(`${newPath}[${index}]`, e.target.value)}
                                />
                                <br /><br />
                            </div>
                        ))}
                    </div>
                </div>
            );
        }
        return (
            <div key={newPath}>
                <label htmlFor={newPath}>{key}:</label>
                <input
                    type="text"
                    id={newPath}
                    name={newPath}
                    value={obj[key]}
                    onChange={(e) => handleChange(newPath, e.target.value)}
                />
                <br /><br />
            </div>
        );
    });
};

const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Submitted Data:', formData);
    // You can process formData or send it to an API endpoint here
};

return (
    <form onSubmit={handleSubmit}>
        {renderFormFields(formData)}
        <button type="submit">Submit</button>
    </form>
);

};

const App = () => { return (

Dynamic JSON Form

); };

export default App;

Flagellate answered 25/6 at 13:14 Comment(1)
Please don't post multiple code-only answers to the same question. Instead, edit your original answer to fix any problems and add some explanation. Please also format your code blocks as shown here. See How do I write a good answer? for more. Thanks, and welcome to Stack Overflow.Limp

© 2022 - 2024 — McMap. All rights reserved.