Dianne
Dianne

Reputation: 196

Dynamically creating react component from fetched data

I am trying to build a fill-in-the-blank style component. It consists of some text with one or more input boxes inside the text. The number and location of the input boxes varies from text to text so the component must be dynamically built. My question is: what is the best way to store this on a database and fetch it for rendering?

My attempt at a solution:

  1. Create a component which has the text and input boxes appropriately placed
  2. Store the entire component JSX in the database and fetch it when requested
  3. Render the fetched JSX in a container component

I think this would work but I'm wondering if there is a better way since it seems a bit hacky to store the entire component JSX on a database.

Upvotes: 0

Views: 1061

Answers (1)

SlothOverlord
SlothOverlord

Reputation: 2037

Do not store the entire element inside the database. You just need to store the relevant data that will go inside the input object:

For example:

initialValue, value, type, placeholder, label, isTextArea, ...etc

Then when you fetch data:

const [inputData, setInputData] = useState(iunitialInputData)

useEffect(() => {
//Fetch input data from DB
data = apiCall()
setInputData(data)
})

return (
//render inputs here

{ inputData?.length? inputData.map(item => {

//Put data inside here
return(
<input value={item.value} placeholder={item.placeholder} />
)
}) : <p>No data!</p>
}
)

Upvotes: 2

Related Questions