Passing a JSON string as props into a react component

This seems to me like a very standard use case, maybe so much so that no one have even considered having to explain it 🙂
But turns out I don’t understand how to achieve it, so please help 🙂

I need to pass a set of data into a react component, the data is optional, and if there isn’t any provided, the component will assume its a new entry.

My problem is that I can get it to work if I assign each variable manually, but now I want to pass the JSON straight as props, saves me having to write a lot of title=data.title, content_id=data.content_id

This is the class (so far)

export interface categoriesEntity {
    'category_id'?: string;
    'category_public'?: boolean | null;
    'description'?: string | null;
    'icon_uri'?: string | null;
    'title'?: string | null;
}

interface withContCategoryEntity extends categoriesEntity {
    newEntity: boolean
}

export class CategoryForm extends React.Component <any, withContCategoryEntity> {
    constructor(props: categoriesEntity) {
        super(props);
        if (props.category_id && (props.category_id ?? false)) {
            this.state = {
                title: props.title,
                category_id: props.category_id,
                icon_uri: props.icon_uri,
                category_public: props.category_public,
                description: props.description,
                newEntity: false
            }
        } else {
            this.state = {
                newEntity: true,
            }
        }

    }
    render() {
        console.log(this.state);

        return <h1>Hello, {this.state.title}</h1>;
    }
}

And if I call it with the line:

           <CategoryForm title={'Test'} category_id={'1'}/>

It works, however, I want to be able to just provide it with JSON, or even better, just a variable with the JSON, something like:

            <CategoryForm {{title: "test", category_id= "123" }}/>

Any help greatly appreciated.

>Solution :

You can just spread your props like this:

<CategoryForm {...categoryFormData} />

It would not work with a JSON itself, because JSON is a string, but it surely should work with objects

For example if you have object

const testData = {
   prop1: "something",
   someMethod: () => console.log("do something")
}

and you will use it like

<CategoryForm {...testData} /> 

it will be same as

<CategoryForm prop1="something" someMethod={() => console.log("do something")} />

Leave a Reply